import inspect
import tempfile
from collections import OrderedDict, UserDict
from collections.abc import MutableMapping
from contextlib import ExitStack, contextmanager
from dataclasses import fields
from enum import Enum
from typing import Any, ContextManager, List, Tuple

import numpy as np

from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy


if is_flax_available():
      import jax.numpy as jnp





class      A							(				UpperCAmelCase_     ):


   def __get__(self     :						Optional[Any]       ,  __UpperCAmelCase     :						Union[str, Any]       ,  __UpperCAmelCase     :						str=None		)						->				str:
         """simple docstring"""



         if obj is None:
               return self
         if self.fget is None:
               raise AttributeError("unreadable attribute"		)
         UpperCAmelCase__								=  "__cached_" + self.fget.__name__
         UpperCAmelCase__								=  getattr(__UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase		)
         if cached is None:
               UpperCAmelCase__								=  self.fget(__UpperCAmelCase		)
               setattr(__UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase		)
         return cached




def    lowerCAmelCase_ (     __A							)     ->				Optional[Any]:







      '''simple docstring'''


      UpperCAmelCase__								=  val.lower()
      if val in {"y", "yes", "t", "true", "on", "1"}:
            return 1
      if val in {"n", "no", "f", "false", "off", "0"}:
            return 0
      raise ValueError(f"""invalid truth value {val!r}"""							)




def    lowerCAmelCase_ (     __A							)     ->				Optional[int]:







      '''simple docstring'''


      if is_torch_fx_proxy(__A							):
            return True
      if is_torch_available():
            import torch

            if isinstance(__A,  torch.Tensor							):
                  return True
      if is_tf_available():
            import tensorflow as tf

            if isinstance(__A,  tf.Tensor							):
                  return True

      if is_flax_available():
            import jax.numpy as jnp
            from jax.core import Tracer

            if isinstance(__A,  (jnp.ndarray, Tracer)							):
                  return True

      return isinstance(__A,  np.ndarray							)




def    lowerCAmelCase_ (     __A							)     ->				str:







      '''simple docstring'''


      return isinstance(__A,  np.ndarray							)




def    lowerCAmelCase_ (     __A							)     ->				List[str]:







      '''simple docstring'''


      return _is_numpy(__A							)




def    lowerCAmelCase_ (     __A							)     ->				Dict:







      '''simple docstring'''


      import torch

      return isinstance(__A,  torch.Tensor							)




def    lowerCAmelCase_ (     __A							)     ->				Optional[int]:







      '''simple docstring'''


      return False if not is_torch_available() else _is_torch(__A							)




def    lowerCAmelCase_ (     __A							)     ->				Union[str, Any]:







      '''simple docstring'''


      import torch

      return isinstance(__A,  torch.device							)




def    lowerCAmelCase_ (     __A							)     ->				Optional[int]:







      '''simple docstring'''


      return False if not is_torch_available() else _is_torch_device(__A							)




def    lowerCAmelCase_ (     __A							)     ->				Any:







      '''simple docstring'''


      import torch

      if isinstance(__A,  __A							):
            if hasattr(__A,  __A							):
                  UpperCAmelCase__								=  getattr(__A,  __A							)
            else:
                  return False
      return isinstance(__A,  torch.dtype							)




def    lowerCAmelCase_ (     __A							)     ->				Tuple:







      '''simple docstring'''


      return False if not is_torch_available() else _is_torch_dtype(__A							)




def    lowerCAmelCase_ (     __A							)     ->				Tuple:







      '''simple docstring'''


      import tensorflow as tf

      return isinstance(__A,  tf.Tensor							)




def    lowerCAmelCase_ (     __A							)     ->				Dict:







      '''simple docstring'''


      return False if not is_tf_available() else _is_tensorflow(__A							)




def    lowerCAmelCase_ (     __A							)     ->				Any:







      '''simple docstring'''


      import tensorflow as tf

      # the `is_symbolic_tensor` predicate is only available starting with TF 2.14
      if hasattr(__A,  "is_symbolic_tensor"							):
            return tf.is_symbolic_tensor(__A							)
      return type(__A							) == tf.Tensor




def    lowerCAmelCase_ (     __A							)     ->				List[str]:







      '''simple docstring'''


      return False if not is_tf_available() else _is_tf_symbolic_tensor(__A							)




def    lowerCAmelCase_ (     __A							)     ->				List[Any]:







      '''simple docstring'''


      import jax.numpy as jnp  # noqa: F811

      return isinstance(__A,  jnp.ndarray							)




def    lowerCAmelCase_ (     __A							)     ->				List[str]:







      '''simple docstring'''


      return False if not is_flax_available() else _is_jax(__A							)




def    lowerCAmelCase_ (     __A							)     ->				Tuple:







      '''simple docstring'''


      if isinstance(__A,  (dict, UserDict)							):
            return {k: to_py_obj(__A							) for k, v in obj.items()}
      elif isinstance(__A,  (list, tuple)							):
            return [to_py_obj(__A							) for o in obj]
      elif is_tf_tensor(__A							):
            return obj.numpy().tolist()
      elif is_torch_tensor(__A							):
            return obj.detach().cpu().tolist()
      elif is_jax_tensor(__A							):
            return np.asarray(__A							).tolist()
      elif isinstance(__A,  (np.ndarray, np.number)							):  # tolist also works on 0d np arrays
            return obj.tolist()
      else:
            return obj




def    lowerCAmelCase_ (     __A							)     ->				Tuple:







      '''simple docstring'''


      if isinstance(__A,  (dict, UserDict)							):
            return {k: to_numpy(__A							) for k, v in obj.items()}
      elif isinstance(__A,  (list, tuple)							):
            return np.array(__A							)
      elif is_tf_tensor(__A							):
            return obj.numpy()
      elif is_torch_tensor(__A							):
            return obj.detach().cpu().numpy()
      elif is_jax_tensor(__A							):
            return np.asarray(__A							)
      else:
            return obj





class      A							(				UpperCAmelCase_     ):


   def 			lowercase_      (self     :						List[Any]		)						->				str:
         """simple docstring"""



         UpperCAmelCase__								=  fields(self		)

         # Safety and consistency checks
         if not len(__UpperCAmelCase		):
               raise ValueError(f"""{self.__class__.__name__} has no fields."""		)
         if not all(field.default is None for field in class_fields[1:]		):
               raise ValueError(f"""{self.__class__.__name__} should not have more than one required field."""		)

         UpperCAmelCase__								=  getattr(self       ,  class_fields[0].name		)
         UpperCAmelCase__								=  all(getattr(self       ,  field.name		) is None for field in class_fields[1:]		)

         if other_fields_are_none and not is_tensor(__UpperCAmelCase		):
               if isinstance(__UpperCAmelCase       ,  __UpperCAmelCase		):
                     UpperCAmelCase__								=  first_field.items()
                     UpperCAmelCase__								=  True
               else:
                     try:
                           UpperCAmelCase__								=  iter(__UpperCAmelCase		)
                           UpperCAmelCase__								=  True
                     except TypeError:
                           UpperCAmelCase__								=  False

            # if we provided an iterator as first field and the iterator is a (key, value) iterator
            # set the associated fields
               if first_field_iterator:
                     for idx, element in enumerate(__UpperCAmelCase		):
                           if (
                               not isinstance(__UpperCAmelCase       ,  (list, tuple)		)
                               or not len(__UpperCAmelCase		) == 2
                               or not isinstance(element[0]       ,  __UpperCAmelCase		)
                           ):
                                 if idx == 0:
                                       # If we do not have an iterator of key/values, set it as attribute
                                       UpperCAmelCase__								=  first_field
                                 else:
                                       # If we have a mixed iterator, raise an error
                                       raise ValueError(
                                           f"""Cannot set key/value for {element}. It needs to be a tuple (key, value)."""		)
                                 break
                           setattr(self       ,  element[0]       ,  element[1]		)
                           if element[1] is not None:
                                 UpperCAmelCase__								=  element[1]
               elif first_field is not None:
                     UpperCAmelCase__								=  first_field
         else:
               for field in class_fields:
                     UpperCAmelCase__								=  getattr(self       ,  field.name		)
                     if v is not None:
                           UpperCAmelCase__								=  v


   def __delitem__(self     :						Any       ,  *__UpperCAmelCase     :						Union[str, Any]       ,  **__UpperCAmelCase     :						Optional[int]		)						->				Optional[int]:
         """simple docstring"""



         raise Exception(f"""You cannot use ``__delitem__`` on a {self.__class__.__name__} instance."""		)


   def 			lowercase_      (self     :						Any       ,  *__UpperCAmelCase     :						int       ,  **__UpperCAmelCase     :						List[Any]		)						->				Union[str, Any]:
         """simple docstring"""



         raise Exception(f"""You cannot use ``setdefault`` on a {self.__class__.__name__} instance."""		)


   def 			lowercase_      (self     :						str       ,  *__UpperCAmelCase     :						Any       ,  **__UpperCAmelCase     :						Optional[int]		)						->				Dict:
         """simple docstring"""



         raise Exception(f"""You cannot use ``pop`` on a {self.__class__.__name__} instance."""		)


   def 			lowercase_      (self     :						List[str]       ,  *__UpperCAmelCase     :						List[str]       ,  **__UpperCAmelCase     :						Any		)						->				Optional[int]:
         """simple docstring"""



         raise Exception(f"""You cannot use ``update`` on a {self.__class__.__name__} instance."""		)


   def __getitem__(self     :						List[str]       ,  __UpperCAmelCase     :						Optional[int]		)						->				Union[str, Any]:
         """simple docstring"""



         if isinstance(__UpperCAmelCase       ,  __UpperCAmelCase		):
               UpperCAmelCase__								=  dict(self.items()		)
               return inner_dict[k]
         else:
               return self.to_tuple()[k]


   def __setattr__(self     :						Dict       ,  __UpperCAmelCase     :						List[Any]       ,  __UpperCAmelCase     :						Optional[int]		)						->				Dict:
         """simple docstring"""



         if name in self.keys() and value is not None:
               # Don't call self.__setitem__ to avoid recursion errors
               super().__setitem__(__UpperCAmelCase       ,  __UpperCAmelCase		)
         super().__setattr__(__UpperCAmelCase       ,  __UpperCAmelCase		)


   def __setitem__(self     :						Dict       ,  __UpperCAmelCase     :						Optional[int]       ,  __UpperCAmelCase     :						List[str]		)						->				int:
         """simple docstring"""



         super().__setitem__(__UpperCAmelCase       ,  __UpperCAmelCase		)
         # Don't call self.__setattr__ to avoid recursion errors
         super().__setattr__(__UpperCAmelCase       ,  __UpperCAmelCase		)





   def 			lowercase_      (self     :						Any		)						->				Tuple[Any]:
         """simple docstring"""



         return tuple(self[k] for k in self.keys()		)





class      A							(				UpperCAmelCase_		,				UpperCAmelCase_     ):


   @classmethod
   def 			lowercase_      (cls     :						List[str]       ,  __UpperCAmelCase     :						int		)						->				Tuple:
         """simple docstring"""



         raise ValueError(
             f"""{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys()		)}"""		)





class      A							(				UpperCAmelCase_     ):
   __UpperCAmelCase : Optional[int]      =			'longest'
   __UpperCAmelCase : int      =			'max_length'
   __UpperCAmelCase : List[str]      =			'do_not_pad'





class      A							(				UpperCAmelCase_     ):
   __UpperCAmelCase : Dict      =			'pt'
   __UpperCAmelCase : Optional[int]      =			'tf'
   __UpperCAmelCase : int      =			'np'
   __UpperCAmelCase : int      =			'jax'





class      A							:


   def __init__(self     :						Union[str, Any]       ,  __UpperCAmelCase     :						List[ContextManager]		)						->				Any:
         """simple docstring"""



         UpperCAmelCase__								=  context_managers
         UpperCAmelCase__								=  ExitStack()


   def __enter__(self     :						Optional[Any]		)						->				List[str]:
         """simple docstring"""



         for context_manager in self.context_managers:
               self.stack.enter_context(__UpperCAmelCase		)





   def __exit__(self     :						List[Any]       ,  *__UpperCAmelCase     :						Tuple       ,  **__UpperCAmelCase     :						str		)						->				Tuple:
         """simple docstring"""



         self.stack.__exit__(*__UpperCAmelCase       ,  **__UpperCAmelCase		)




def    lowerCAmelCase_ (     __A							)     ->				Any:







      '''simple docstring'''


      UpperCAmelCase__								=  infer_framework(__A							)
      if framework == "tf":
            UpperCAmelCase__								=  inspect.signature(model_class.call							)  # TensorFlow models
      elif framework == "pt":
            UpperCAmelCase__								=  inspect.signature(model_class.forward							)  # PyTorch models
      else:
            UpperCAmelCase__								=  inspect.signature(model_class.__call__							)  # Flax models

      for p in signature.parameters:
            if p == "return_loss" and signature.parameters[p].default is True:
                  return True

      return False




def    lowerCAmelCase_ (     __A							)     ->				Dict:







      '''simple docstring'''


      UpperCAmelCase__								=  model_class.__name__
      UpperCAmelCase__								=  infer_framework(__A							)
      if framework == "tf":
            UpperCAmelCase__								=  inspect.signature(model_class.call							)  # TensorFlow models
      elif framework == "pt":
            UpperCAmelCase__								=  inspect.signature(model_class.forward							)  # PyTorch models
      else:
            UpperCAmelCase__								=  inspect.signature(model_class.__call__							)  # Flax models

      if "QuestionAnswering" in model_name:
            return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")]
      else:
            return [p for p in signature.parameters if "label" in p]




def    lowerCAmelCase_ (     __A,  __A = "",  __A = "."							)     ->				Tuple:







      '''simple docstring'''


      def _flatten_dict(__A,  __A="",  __A="."							):
            for k, v in d.items():
                  UpperCAmelCase__								=  str(__A							) + delimiter + str(__A							) if parent_key else k
                  if v and isinstance(__A,  __A							):
                        yield from flatten_dict(__A,  __A,  delimiter=__A							).items()
                  else:
                        yield key, v

      return dict(_flatten_dict(__A,  __A,  __A							)							)




@contextmanager
def    lowerCAmelCase_ (     __A,  __A = False							)     ->				Dict:







      '''simple docstring'''


      if use_temp_dir:
            with tempfile.TemporaryDirectory() as tmp_dir:
                  yield tmp_dir
      else:
            yield working_dir




def    lowerCAmelCase_ (     __A,  __A=None							)     ->				int:







      '''simple docstring'''


      if is_numpy_array(__A							):
            return np.transpose(__A,  axes=__A							)
      elif is_torch_tensor(__A							):
            return array.T if axes is None else array.permute(*__A							)
      elif is_tf_tensor(__A							):
            import tensorflow as tf

            return tf.transpose(__A,  perm=__A							)
      elif is_jax_tensor(__A							):
            return jnp.transpose(__A,  axes=__A							)
      else:
            raise ValueError(f"""Type not supported for transpose: {type(__A							)}."""							)




def    lowerCAmelCase_ (     __A,  __A							)     ->				List[str]:







      '''simple docstring'''


      if is_numpy_array(__A							):
            return np.reshape(__A,  __A							)
      elif is_torch_tensor(__A							):
            return array.reshape(*__A							)
      elif is_tf_tensor(__A							):
            import tensorflow as tf

            return tf.reshape(__A,  __A							)
      elif is_jax_tensor(__A							):
            return jnp.reshape(__A,  __A							)
      else:
            raise ValueError(f"""Type not supported for reshape: {type(__A							)}."""							)




def    lowerCAmelCase_ (     __A,  __A=None							)     ->				str:







      '''simple docstring'''


      if is_numpy_array(__A							):
            return np.squeeze(__A,  axis=__A							)
      elif is_torch_tensor(__A							):
            return array.squeeze() if axis is None else array.squeeze(dim=__A							)
      elif is_tf_tensor(__A							):
            import tensorflow as tf

            return tf.squeeze(__A,  axis=__A							)
      elif is_jax_tensor(__A							):
            return jnp.squeeze(__A,  axis=__A							)
      else:
            raise ValueError(f"""Type not supported for squeeze: {type(__A							)}."""							)




def    lowerCAmelCase_ (     __A,  __A							)     ->				Optional[Any]:







      '''simple docstring'''


      if is_numpy_array(__A							):
            return np.expand_dims(__A,  __A							)
      elif is_torch_tensor(__A							):
            return array.unsqueeze(dim=__A							)
      elif is_tf_tensor(__A							):
            import tensorflow as tf

            return tf.expand_dims(__A,  axis=__A							)
      elif is_jax_tensor(__A							):
            return jnp.expand_dims(__A,  axis=__A							)
      else:
            raise ValueError(f"""Type not supported for expand_dims: {type(__A							)}."""							)




def    lowerCAmelCase_ (     __A							)     ->				Optional[int]:







      '''simple docstring'''


      if is_numpy_array(__A							):
            return np.size(__A							)
      elif is_torch_tensor(__A							):
            return array.numel()
      elif is_tf_tensor(__A							):
            import tensorflow as tf

            return tf.size(__A							)
      elif is_jax_tensor(__A							):
            return array.size
      else:
            raise ValueError(f"""Type not supported for expand_dims: {type(__A							)}."""							)




def    lowerCAmelCase_ (     __A,  __A							)     ->				Dict:







      '''simple docstring'''


      for key, value in auto_map.items():
            if isinstance(__A,  (tuple, list)							):
                  UpperCAmelCase__								=  [f"""{repo_id}--{v}""" if (v is not None and "--" not in v) else v for v in value]
            elif value is not None and "--" not in value:
                  UpperCAmelCase__								=  f"""{repo_id}--{value}"""

      return auto_map







def    lowerCAmelCase_ (     __A							)     ->				Optional[Any]:







      '''simple docstring'''


      for base_class in inspect.getmro(__A							):
            UpperCAmelCase__								=  base_class.__module__
            UpperCAmelCase__								=  base_class.__name__
            if module.startswith("tensorflow"							) or module.startswith("keras"							) or name == "TFPreTrainedModel":
                  return "tf"
            elif module.startswith("torch"							) or name == "PreTrainedModel":
                  return "pt"
            elif module.startswith("flax"							) or module.startswith("jax"							) or name == "FlaxPreTrainedModel":
                  return "flax"
      else:
            raise TypeError(f"""Could not infer framework from class {model_class}."""							)




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_ (     __A,  __A=False							)     ->				Any:







      '''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


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

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

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

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




def    lowerCAmelCase_ (     __A							)     ->				Any:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				Optional[Any]:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				List[str]:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				List[Any]:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				List[str]:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				Union[str, Any]:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				Any:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				int:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				Tuple:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				Dict:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				Optional[Any]:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				Optional[int]:







      '''simple docstring'''


      def _require_spacy_model(__A							):
            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_ (     __A							)     ->				Optional[Any]:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				Tuple:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				Optional[int]:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				List[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_ (     __A							)     ->				Optional[Any]:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				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_ (     *__A							)     ->				Optional[int]:







      '''simple docstring'''


      def decorate(cls							):
            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      A							(				UpperCAmelCase_     ):
   pass





class      A							(				UpperCAmelCase_     ):
   __UpperCAmelCase : Union[str, Any]      =			0
   __UpperCAmelCase : str      =			1
   __UpperCAmelCase : int      =			2




@contextmanager
def    lowerCAmelCase_ (     __A=OfflineSimulationMode.CONNECTION_FAILS,  __A=1e-16							)     ->				List[str]:







      '''simple docstring'''


      UpperCAmelCase__								=  requests.Session().request

      def timeout_request(__A,  __A,  __A,  **__A							):
            # 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(__A,  __A,  **__A							):
            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_ (     *__A,  **__A							)     ->				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_ (     )     ->				Optional[Any]:







      '''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_ (     )     ->				List[str]:







      '''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_ (     __A,  __A							)     ->				List[str]:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				Optional[int]:







      '''simple docstring'''


      import decorator
      from requests.exceptions import HTTPError

      def _wrapper(__A,  *__A,  **__A							):
            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      A							:


   def __init__(self     :						Optional[Any]       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						List[str]		)						->				Union[str, Any]:
         """simple docstring"""



         UpperCAmelCase__								=  returncode
         UpperCAmelCase__								=  stdout
         UpperCAmelCase__								=  stderr




async def    lowerCAmelCase_ (     __A,  __A							)     ->				Optional[int]:







      '''simple docstring'''


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




async def    lowerCAmelCase_ (     __A,  __A=None,  __A=None,  __A=None,  __A=False,  __A=False							)     ->				_RunOutput:







      '''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(__A,  __A,  __A,  __A=""							):
            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 __A							: tee(__A,  __A,  sys.stdout,  label="stdout:"							)							),
              _read_stream(p.stderr,  lambda __A							: tee(__A,  __A,  sys.stderr,  label="stderr:"							)							),
          ],  timeout=__A,  )
      return _RunOutput(await p.wait(),  __A,  __A							)




def    lowerCAmelCase_ (     __A,  __A=None,  __A=None,  __A=180,  __A=False,  __A=True							)     ->				_RunOutput:







      '''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_ (     )     ->				Tuple:







      '''simple docstring'''


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







def    lowerCAmelCase_ (     )     ->				List[Any]:







      '''simple docstring'''


      UpperCAmelCase__								=  29_500
      UpperCAmelCase__								=  pytest_xdist_worker_id()
      return port + uniq_delta



