





import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse("""3.8"""):
      import importlib_metadata
else:
      import importlib.metadata as importlib_metadata


def     lowerCamelCase_	(      lowerCAmelCase:	Optional[int]    ,							lowerCAmelCase:	int=False				)->		Union[str, Any]:






  try:
    _snake_case   :				Optional[Any]														=	os.environ[key]
  except KeyError:
    # KEY isn't set, default to `default`.
    _snake_case   :				Optional[int]														=	default
  else:
    # KEY is set, convert it to True or False.
    try:
      _snake_case   :				List[str]														=	strtobool(a_				)
    except ValueError:
      # More values are supported, but let's keep the message simple.
      raise ValueError(F"""If set, {key} must be yes or no."""				)
  return _value


lowerCAmelCase_						   =    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     lowerCamelCase_	(      lowerCAmelCase:	Optional[Any]				)->		Dict:






  try:
    import faiss  # noqa
  except ImportError:
    _snake_case   :				Dict														=	unittest.skip('test requires faiss'				)(a_				)
  return test_case


def     lowerCamelCase_	(      lowerCAmelCase:	Any				)->		Optional[int]:






  try:
    import regex  # noqa
  except ImportError:
    _snake_case   :				int														=	unittest.skip('test requires regex'				)(a_				)
  return test_case


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






  try:
    import elasticsearch  # noqa
  except ImportError:
    _snake_case   :				Optional[int]														=	unittest.skip('test requires elasticsearch'				)(a_				)
  return test_case


def     lowerCamelCase_	(      lowerCAmelCase:	int				)->		Tuple:






  try:
    import sqlalchemy  # noqa
  except ImportError:
    _snake_case   :				List[str]														=	unittest.skip('test requires sqlalchemy'				)(a_				)
  return test_case


def     lowerCamelCase_	(      lowerCAmelCase:	Optional[Any]				)->		int:






  if not config.TORCH_AVAILABLE:
    _snake_case   :				List[Any]														=	unittest.skip('test requires PyTorch'				)(a_				)
  return test_case


def     lowerCamelCase_	(      lowerCAmelCase:	int				)->		List[Any]:






  if not config.TF_AVAILABLE:
    _snake_case   :				Any														=	unittest.skip('test requires TensorFlow'				)(a_				)
  return test_case


def     lowerCamelCase_	(      lowerCAmelCase:	Dict				)->		Any:






  if not config.JAX_AVAILABLE:
    _snake_case   :				List[str]														=	unittest.skip('test requires JAX'				)(a_				)
  return test_case


def     lowerCamelCase_	(      lowerCAmelCase:	Optional[Any]				)->		Any:






  if not config.PIL_AVAILABLE:
    _snake_case   :				List[Any]														=	unittest.skip('test requires Pillow'				)(a_				)
  return test_case


def     lowerCamelCase_	(      lowerCAmelCase:	Optional[Any]				)->		Tuple:






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


def     lowerCamelCase_	(      lowerCAmelCase:	Tuple				)->		Optional[int]:






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


def     lowerCamelCase_	(      lowerCAmelCase:	Union[str, Any]				)->		int:






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


def     lowerCamelCase_	(      lowerCAmelCase:	Tuple				)->		int:






  def _require_spacy_model(lowerCAmelCase:	Optional[int]				):
    try:
      import spacy  # noqa F401

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

  return _require_spacy_model


def     lowerCamelCase_	(      lowerCAmelCase:	str				)->		int:






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


def     lowerCamelCase_	(      lowerCAmelCase:	List[Any]				)->		Optional[Any]:






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


def     lowerCamelCase_	(      lowerCAmelCase:	Dict				)->		str:






  if not _run_slow_tests or _run_slow_tests == 0:
    _snake_case   :				Union[str, Any]														=	unittest.skip('test is slow'				)(a_				)
  return test_case


def     lowerCamelCase_	(      lowerCAmelCase:	str				)->		List[Any]:






  if not _run_local_tests or _run_local_tests == 0:
    _snake_case   :				Optional[int]														=	unittest.skip('test is local'				)(a_				)
  return test_case


def     lowerCamelCase_	(      lowerCAmelCase:	str				)->		str:






  if not _run_packaged_tests or _run_packaged_tests == 0:
    _snake_case   :				int														=	unittest.skip('test is packaged'				)(a_				)
  return test_case


def     lowerCamelCase_	(      lowerCAmelCase:	str				)->		Tuple:






  if not _run_remote_tests or _run_remote_tests == 0:
    _snake_case   :				Optional[int]														=	unittest.skip('test requires remote'				)(a_				)
  return test_case


def     lowerCamelCase_	(      *lowerCAmelCase:	int				)->		Tuple:






  def decorate(cls:	Any				):
    for name, fn in cls.__dict__.items():
      if callable(a_				) and name.startswith('test'				):
        for decorator in decorators:
          _snake_case   :				Optional[Any]														=	decorator(a_				)
        setattr(cls    ,							a_    ,							a_				)
    return cls

  return decorate



class        _lowerCAmelCase    (			_UpperCAmelCase							):


  '''simple docstring'''
  pass




class        _lowerCAmelCase    (			_UpperCAmelCase							):


  '''simple docstring'''
  a_							:       Optional[Any]      					=0
  a_							:       Any      					=1
  a_							:       int      					=2




@contextmanager
def     lowerCamelCase_	(      lowerCAmelCase:	List[str]=OfflineSimulationMode.CONNECTION_FAILS    ,							lowerCAmelCase:	List[Any]=1E-16				)->		str:
  _snake_case   :				List[Any]														=	requests.Session().request

  def timeout_request(lowerCAmelCase:	int    ,							lowerCAmelCase:	int    ,							lowerCAmelCase:	Dict    ,							**lowerCAmelCase:	Tuple				):
    # 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   :				Dict														=	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
      _snake_case   :				int														=	url
      _snake_case   :				Any														=	e.args[0]
      _snake_case   :				Optional[int]														=	(max_retry_error.args[0].replace('10.255.255.1'    ,							F"""OfflineMock[{url}]"""				),)
      _snake_case   :				Union[str, Any]														=	(max_retry_error,)
      raise

  def raise_connection_error(lowerCAmelCase:	Dict    ,							lowerCAmelCase:	Dict    ,							**lowerCAmelCase:	List[Any]				):
    raise requests.ConnectionError('Offline mode is enabled.'    ,							request=a_				)

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


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


@contextmanager
def     lowerCamelCase_	(      )->		Optional[int]:
  import gc

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


@contextmanager
def     lowerCamelCase_	(      )->		List[str]:
  import gc

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


def     lowerCamelCase_	(      lowerCAmelCase:	Any    ,							lowerCAmelCase:	str				)->		List[str]:
  return deepcopy(a_				).integers(0    ,							1_00    ,							10				).tolist() == deepcopy(a_				).integers(0    ,							1_00    ,							10				).tolist()


def     lowerCamelCase_	(      lowerCAmelCase:	Tuple				)->		Tuple:
  import decorator
  from requests.exceptions import HTTPError

  def _wrapper(lowerCAmelCase:	Dict    ,							*lowerCAmelCase:	int    ,							**lowerCAmelCase:	Tuple				):
    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        _lowerCAmelCase    :


  '''simple docstring'''







  def __init__(      self      :					List[str]      ,				UpperCamelCase      :					Any      ,				UpperCamelCase      :					int      ,				UpperCamelCase      :					List[str]							)     ->   List[str]:


    '''simple docstring'''





    _snake_case   :				Any														=	returncode
    _snake_case   :				int														=	stdout
    _snake_case   :				Tuple														=	stderr




async def     lowerCamelCase_	(      lowerCAmelCase:	List[str]    ,							lowerCAmelCase:	Optional[int]				)->		Tuple:






  while True:
    _snake_case   :				int														=	await stream.readline()
    if line:
      callback(a_				)
    else:
      break


async def     lowerCamelCase_	(      lowerCAmelCase:	Optional[int]    ,							lowerCAmelCase:	Optional[Any]=None    ,							lowerCAmelCase:	int=None    ,							lowerCAmelCase:	int=None    ,							lowerCAmelCase:	List[str]=False    ,							lowerCAmelCase:	Optional[Any]=False				)->		_RunOutput:






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

  _snake_case   :				Dict														=	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)

  _snake_case   :				str														=	[]
  _snake_case   :				Tuple														=	[]

  def tee(lowerCAmelCase:	int    ,							lowerCAmelCase:	Tuple    ,							lowerCAmelCase:	Any    ,							lowerCAmelCase:	Optional[Any]=""				):
    _snake_case   :				Union[str, Any]														=	line.decode('utf-8'				).rstrip()
    sink.append(a_				)
    if not quiet:
      print(a_    ,							a_    ,							file=a_				)

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


def     lowerCamelCase_	(      lowerCAmelCase:	Optional[Any]    ,							lowerCAmelCase:	Any=None    ,							lowerCAmelCase:	List[str]=None    ,							lowerCAmelCase:	Tuple=1_80    ,							lowerCAmelCase:	List[Any]=False    ,							lowerCAmelCase:	str=True				)->		_RunOutput:
  _snake_case   :				int														=	asyncio.get_event_loop()
  _snake_case   :				Any														=	loop.run_until_complete(
      _stream_subprocess(a_    ,							env=a_    ,							stdin=a_    ,							timeout=a_    ,							quiet=a_    ,							echo=a_				)				)

  _snake_case   :				Optional[Any]														=	''' '''.join(a_				)
  if result.returncode > 0:
    _snake_case   :				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     lowerCamelCase_	(      )->		List[str]:
  _snake_case   :				List[Any]														=	os.environ.get('PYTEST_XDIST_WORKER'    ,							'gw0'				)
  _snake_case   :				Union[str, Any]														=	re.sub(R'^gw'    ,							''    ,							a_    ,							0    ,							re.M				)
  return int(a_				)







def     lowerCamelCase_	(      )->		Tuple:
  _snake_case   :				Any														=	2_95_00
  _snake_case   :				str														=	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""": 512,
}

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



class        _lowerCAmelCase    (			UpperCAmelCase_							):


  '''simple docstring'''
  a_							:       List[Any]      					=VOCAB_FILES_NAMES
  a_							:       Tuple      					=PRETRAINED_VOCAB_FILES_MAP
  a_							:       Optional[Any]      					=PRETRAINED_INIT_CONFIGURATION
  a_							:       Any      					=PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  a_							:       Any      					=LxmertTokenizer







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


    '''simple docstring'''





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

    _snake_case   :				Tuple														=	json.loads(self.backend_tokenizer.normalizer.__getstate__()							)
    if (
        normalizer_state.get('lowercase'      ,				UpperCamelCase							) != do_lower_case
        or normalizer_state.get('strip_accents'      ,				UpperCamelCase							) != strip_accents
        or normalizer_state.get('handle_chinese_chars'      ,				UpperCamelCase							) != tokenize_chinese_chars
    ):
      _snake_case   :				List[Any]														=	getattr(UpperCamelCase      ,				normalizer_state.pop('type'							)							)
      _snake_case   :				Optional[int]														=	do_lower_case
      _snake_case   :				Dict														=	strip_accents
      _snake_case   :				Optional[int]														=	tokenize_chinese_chars
      _snake_case   :				Optional[Any]														=	normalizer_class(**UpperCamelCase							)

    _snake_case   :				int														=	do_lower_case







  def UpperCamelCase_ (      self      :					int      ,				UpperCamelCase      :					List[str]      ,				UpperCamelCase      :					str=None							):


    '''simple docstring'''





    _snake_case   :				List[Any]														=	[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 UpperCamelCase_ (      self      :					List[str]      ,				UpperCamelCase      :					List[int]      ,				UpperCamelCase      :					Optional[List[int]] = None							):


    '''simple docstring'''





    _snake_case   :				Tuple														=	[self.sep_token_id]
    _snake_case   :				List[str]														=	[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 UpperCamelCase_ (      self      :					int      ,				UpperCamelCase      :					str      ,				UpperCamelCase      :					Optional[str] = None							):


    '''simple docstring'''





    _snake_case   :				int														=	self._tokenizer.model.save(UpperCamelCase      ,				name=UpperCamelCase							)
    return tuple(UpperCamelCase							)




