
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 			UpperCamelCase					(    __lowerCamelCase     : Dict				,					__lowerCamelCase     : str=False    ):
       try:
              snake_case       :   Union[str, Any]							=      os.environ[key]
       except KeyError:
              # KEY isn't set, default to `default`.
              snake_case       :   Tuple							=      default
       else:
              # KEY is set, convert it to True or False.
              try:
                     snake_case       :   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


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

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

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

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


def 			UpperCamelCase					(    __lowerCamelCase     : Tuple    ):
       try:
              import faiss  # noqa
       except ImportError:
              snake_case       :   int							=      unittest.skip("test requires faiss"    )(__lowerCamelCase    )
       return test_case


def 			UpperCamelCase					(    __lowerCamelCase     : Dict    ):
       try:
              import regex  # noqa
       except ImportError:
              snake_case       :   Optional[Any]							=      unittest.skip("test requires regex"    )(__lowerCamelCase    )
       return test_case


def 			UpperCamelCase					(    __lowerCamelCase     : Tuple    ):
       try:
              import elasticsearch  # noqa
       except ImportError:
              snake_case       :   Optional[Any]							=      unittest.skip("test requires elasticsearch"    )(__lowerCamelCase    )
       return test_case


def 			UpperCamelCase					(    __lowerCamelCase     : List[str]    ):
       try:
              import sqlalchemy  # noqa
       except ImportError:
              snake_case       :   Any							=      unittest.skip("test requires sqlalchemy"    )(__lowerCamelCase    )
       return test_case


def 			UpperCamelCase					(    __lowerCamelCase     : Optional[int]    ):
       if not config.TORCH_AVAILABLE:
              snake_case       :   Any							=      unittest.skip("test requires PyTorch"    )(__lowerCamelCase    )
       return test_case


def 			UpperCamelCase					(    __lowerCamelCase     : Tuple    ):
       if not config.TF_AVAILABLE:
              snake_case       :   int							=      unittest.skip("test requires TensorFlow"    )(__lowerCamelCase    )
       return test_case


def 			UpperCamelCase					(    __lowerCamelCase     : Union[str, Any]    ):
       if not config.JAX_AVAILABLE:
              snake_case       :   List[Any]							=      unittest.skip("test requires JAX"    )(__lowerCamelCase    )
       return test_case


def 			UpperCamelCase					(    __lowerCamelCase     : Dict    ):
       if not config.PIL_AVAILABLE:
              snake_case       :   List[str]							=      unittest.skip("test requires Pillow"    )(__lowerCamelCase    )
       return test_case


def 			UpperCamelCase					(    __lowerCamelCase     : Optional[int]    ):
       try:
              import transformers  # noqa F401
       except ImportError:
              return unittest.skip("test requires transformers"    )(__lowerCamelCase    )
       else:
              return test_case


def 			UpperCamelCase					(    __lowerCamelCase     : List[str]    ):
       try:
              import tiktoken  # noqa F401
       except ImportError:
              return unittest.skip("test requires tiktoken"    )(__lowerCamelCase    )
       else:
              return test_case


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


def 			UpperCamelCase					(    __lowerCamelCase     : Optional[int]    ):

       def _require_spacy_model(__lowerCamelCase     : Optional[Any]    ):
              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 			UpperCamelCase					(    __lowerCamelCase     : Dict    ):
       try:
              import pyspark  # noqa F401
       except ImportError:
              return unittest.skip("test requires pyspark"    )(__lowerCamelCase    )
       else:
              return test_case


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


def 			UpperCamelCase					(    __lowerCamelCase     : Dict    ):
       if not _run_slow_tests or _run_slow_tests == 0:
              snake_case       :   Union[str, Any]							=      unittest.skip("test is slow"    )(__lowerCamelCase    )
       return test_case


def 			UpperCamelCase					(    __lowerCamelCase     : Union[str, Any]    ):
       if not _run_local_tests or _run_local_tests == 0:
              snake_case       :   List[str]							=      unittest.skip("test is local"    )(__lowerCamelCase    )
       return test_case


def 			UpperCamelCase					(    __lowerCamelCase     : Dict    ):
       if not _run_packaged_tests or _run_packaged_tests == 0:
              snake_case       :   Tuple							=      unittest.skip("test is packaged"    )(__lowerCamelCase    )
       return test_case


def 			UpperCamelCase					(    __lowerCamelCase     : Any    ):
       if not _run_remote_tests or _run_remote_tests == 0:
              snake_case       :   int							=      unittest.skip("test requires remote"    )(__lowerCamelCase    )
       return test_case


def 			UpperCamelCase					(    *__lowerCamelCase     : Dict    ):
       def decorate(cls     : Union[str, Any]    ):
              for name, fn in cls.__dict__.items():
                     if callable(__lowerCamelCase    ) and name.startswith("test"    ):
                            for decorator in decorators:
                                   snake_case       :   Optional[int]							=      decorator(__lowerCamelCase    )
                            setattr(cls				,					__lowerCamelCase				,					__lowerCamelCase    )
              return cls

       return decorate






class   UpperCAmelCase		(						A_ ):
   pass






class   UpperCAmelCase		(						A_ ):
   A__					:		str						     =     0
   A__					:		Optional[Any]						     =     1
   A__					:		Optional[Any]						     =     2



@contextmanager
def 			UpperCamelCase					(    __lowerCamelCase     : Tuple=OfflineSimulationMode.CONNECTION_FAILS				,					__lowerCamelCase     : Tuple=1E-16    ):
       snake_case       :   Dict							=      requests.Session().request

       def timeout_request(__lowerCamelCase     : Dict				,					__lowerCamelCase     : List[str]				,					__lowerCamelCase     : List[Any]				,					**__lowerCamelCase     : List[Any]    ):
              # Change the url to an invalid url so that the connection hangs
              snake_case       :   Union[str, Any]							=      "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."""    )
              snake_case       :   Optional[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
                     snake_case       :   Union[str, Any]							=      url
                     snake_case       :   Union[str, Any]							=      e.args[0]
                     snake_case       :   Optional[int]							=      (max_retry_error.args[0].replace("10.255.255.1"				,					f"""OfflineMock[{url}]"""    ),)
                     snake_case       :   Any							=      (max_retry_error,)
                     raise

       def raise_connection_error(__lowerCamelCase     : Tuple				,					__lowerCamelCase     : Optional[Any]				,					**__lowerCamelCase     : List[Any]    ):
              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 			UpperCamelCase					(    *__lowerCamelCase     : Any				,					**__lowerCamelCase     : Optional[Any]    ):
       snake_case       :   str							=      str(Path().resolve()    )
       with tempfile.TemporaryDirectory(*__lowerCamelCase				,					**__lowerCamelCase    ) as tmp_dir:
              try:
                     os.chdir(__lowerCamelCase    )
                     yield
              finally:
                     os.chdir(__lowerCamelCase    )


@contextmanager
def 			UpperCamelCase					(    ):
       import gc

       gc.collect()
       snake_case       :   Optional[int]							=      pa.total_allocated_bytes()
       yield
       assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."


@contextmanager
def 			UpperCamelCase					(    ):
       import gc

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


def 			UpperCamelCase					(    __lowerCamelCase     : List[Any]				,					__lowerCamelCase     : Dict    ):
       return deepcopy(__lowerCamelCase    ).integers(0				,					100				,					10    ).tolist() == deepcopy(__lowerCamelCase    ).integers(0				,					100				,					10    ).tolist()


def 			UpperCamelCase					(    __lowerCamelCase     : Dict    ):
       import decorator
       from requests.exceptions import HTTPError

       def _wrapper(__lowerCamelCase     : Optional[int]				,					*__lowerCamelCase     : int				,					**__lowerCamelCase     : int    ):
              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   UpperCAmelCase		:



   def __init__(self		:					Dict    ,						snake_case__		:					List[str]    ,						snake_case__		:					int    ,						snake_case__		:					Any )		->	Optional[int]:


          '''simple docstring'''


          snake_case       :   List[str]							=      returncode
          snake_case       :   str							=      stdout
          snake_case       :   Union[str, Any]							=      stderr



async def 			UpperCamelCase					(    __lowerCamelCase     : Optional[Any]				,					__lowerCamelCase     : Dict    ):
       while True:
              snake_case       :   Any							=      await stream.readline()
              if line:
                     callback(__lowerCamelCase    )
              else:
                     break


async def 			UpperCamelCase					(    __lowerCamelCase     : List[str]				,					__lowerCamelCase     : int=None				,					__lowerCamelCase     : Tuple=None				,					__lowerCamelCase     : Optional[Any]=None				,					__lowerCamelCase     : str=False				,					__lowerCamelCase     : int=False    ):
       if echo:
              print("\nRunning: "				,					" ".join(__lowerCamelCase    )    )

       snake_case       :   List[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)

       snake_case       :   Dict							=      []
       snake_case       :   Optional[Any]							=      []

       def tee(__lowerCamelCase     : Union[str, Any]				,					__lowerCamelCase     : str				,					__lowerCamelCase     : Optional[Any]				,					__lowerCamelCase     : int=""    ):
              snake_case       :   Dict							=      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 			UpperCamelCase					(    __lowerCamelCase     : Optional[Any]				,					__lowerCamelCase     : Optional[int]=None				,					__lowerCamelCase     : Any=None				,					__lowerCamelCase     : int=180				,					__lowerCamelCase     : List[str]=False				,					__lowerCamelCase     : int=True    ):
       snake_case       :   Optional[int]							=      asyncio.get_event_loop()
       snake_case       :   List[str]							=      loop.run_until_complete(
           _stream_subprocess(__lowerCamelCase				,					env=__lowerCamelCase				,					stdin=__lowerCamelCase				,					timeout=__lowerCamelCase				,					quiet=__lowerCamelCase				,					echo=__lowerCamelCase    )    )

       snake_case       :   Union[str, Any]							=      " ".join(__lowerCamelCase    )
       if result.returncode > 0:
              snake_case       :   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 			UpperCamelCase					(    ):
       snake_case       :   List[Any]							=      os.environ.get("PYTEST_XDIST_WORKER"				,					"gw0"    )
       snake_case       :   List[str]							=      re.sub(r"^gw"				,					""				,					__lowerCamelCase				,					0				,					re.M    )
       return int(__lowerCamelCase    )




def 			UpperCamelCase					(    ):
       snake_case       :   Any							=      29500
       snake_case       :   Dict							=      pytest_xdist_worker_id()
       return port + uniq_delta







import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from .tokenization_lxmert import LxmertTokenizer


__lowerCamelCase							=       {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""}

__lowerCamelCase							=       {
    """vocab_file""": {
        """unc-nlp/lxmert-base-uncased""": """https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/vocab.txt""",
    },
    """tokenizer_file""": {
        """unc-nlp/lxmert-base-uncased""": (
            """https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/tokenizer.json"""
        ),
    },
}

__lowerCamelCase							=       {
    """unc-nlp/lxmert-base-uncased""": 5_12,
}

__lowerCamelCase							=       {
    """unc-nlp/lxmert-base-uncased""": {"""do_lower_case""": True},
}






class   UpperCAmelCase		(						A_ ):
   A__					:		Any						     =     VOCAB_FILES_NAMES
   A__					:		Optional[int]						     =     PRETRAINED_VOCAB_FILES_MAP
   A__					:		Tuple						     =     PRETRAINED_INIT_CONFIGURATION
   A__					:		Tuple						     =     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   A__					:		List[Any]						     =     LxmertTokenizer



   def __init__(self		:					Dict    ,						snake_case__		:					Tuple=None    ,						snake_case__		:					Optional[Any]=None    ,						snake_case__		:					Optional[Any]=True    ,						snake_case__		:					Tuple="[UNK]"    ,						snake_case__		:					Optional[Any]="[SEP]"    ,						snake_case__		:					Optional[Any]="[PAD]"    ,						snake_case__		:					List[Any]="[CLS]"    ,						snake_case__		:					Tuple="[MASK]"    ,						snake_case__		:					Dict=True    ,						snake_case__		:					Union[str, Any]=None    ,						**snake_case__		:					Dict    ,						)		->	Optional[int]:


          '''simple docstring'''


          super().__init__(
              snake_case__    ,						tokenizer_file=snake_case__    ,						do_lower_case=snake_case__    ,						unk_token=snake_case__    ,						sep_token=snake_case__    ,						pad_token=snake_case__    ,						cls_token=snake_case__    ,						mask_token=snake_case__    ,						tokenize_chinese_chars=snake_case__    ,						strip_accents=snake_case__    ,						**snake_case__    ,						)

          snake_case       :   int							=      json.loads(self.backend_tokenizer.normalizer.__getstate__() )
          if (
              normalizer_state.get("lowercase"    ,						snake_case__ ) != do_lower_case
              or normalizer_state.get("strip_accents"    ,						snake_case__ ) != strip_accents
              or normalizer_state.get("handle_chinese_chars"    ,						snake_case__ ) != tokenize_chinese_chars
          ):
                 snake_case       :   Union[str, Any]							=      getattr(snake_case__    ,						normalizer_state.pop("type" ) )
                 snake_case       :   str							=      do_lower_case
                 snake_case       :   List[Any]							=      strip_accents
                 snake_case       :   Optional[int]							=      tokenize_chinese_chars
                 snake_case       :   int							=      normalizer_class(**snake_case__ )

          snake_case       :   Optional[Any]							=      do_lower_case



   def 				_SCREAMING_SNAKE_CASE   (self		:					Union[str, Any]    ,						snake_case__		:					Optional[Any]    ,						snake_case__		:					Dict=None )		->	Any:


          '''simple docstring'''


          snake_case       :   Optional[int]							=      [self.cls_token_id] + token_ids_a + [self.sep_token_id]

          if token_ids_a:
                 output += token_ids_a + [self.sep_token_id]

          return output



   def 				_SCREAMING_SNAKE_CASE   (self		:					Optional[int]    ,						snake_case__		:					List[int]    ,						snake_case__		:					Optional[List[int]] = None )		->	List[int]:


          '''simple docstring'''


          snake_case       :   Optional[Any]							=      [self.sep_token_id]
          snake_case       :   Optional[Any]							=      [self.cls_token_id]
          if token_ids_a is None:
                 return len(cls + token_ids_a + sep ) * [0]
          return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]



   def 				_SCREAMING_SNAKE_CASE   (self		:					Any    ,						snake_case__		:					str    ,						snake_case__		:					Optional[str] = None )		->	Tuple[str]:


          '''simple docstring'''


          snake_case       :   List[Any]							=      self._tokenizer.model.save(snake_case__    ,						name=snake_case__ )
          return tuple(snake_case__ )





