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

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

from datasets import config


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


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


A   :     Union[str, Any]       =				parse_flag_from_env("RUN_SLOW", default=False)
A   :     Any       =				parse_flag_from_env("RUN_REMOTE", default=False)
A   :     List[Any]       =				parse_flag_from_env("RUN_LOCAL", default=True)
A   :     Optional[int]       =				parse_flag_from_env("RUN_PACKAGED", default=True)

# Compression
A   :     Optional[int]       =				pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="test requires lz4")
A   :     Dict       =				pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="test requires py7zr")
A   :     Tuple       =				pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="test requires zstandard")

# Audio
A   :     Dict       =				pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec("soundfile") is None or version.parse(importlib_metadata.version("soundfile")) < version.parse("0.12.0"),
    reason="test requires sndfile>=0.12.1: 'pip install \"soundfile>=0.12.1\"'; ",
)

# Beam
A   :     Union[str, Any]       =				pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse("0.3.2"),
    reason="test requires apache-beam and a compatible dill version",
)

# Dill-cloudpickle compatibility
A   :     Any       =				pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("0.3.2"),
    reason="test requires dill>0.3.2 for cloudpickle compatibility",
)

# Windows
A   :     Union[str, Any]       =				pytest.mark.skipif(
    sys.platform == "win32",
    reason="test should not be run on Windows",
)


def    a__       (						__UpperCamelCase ):
      try:
            import faiss  # noqa
      except ImportError:
            SCREAMING_SNAKE_CASE_      =     unittest.skip("test requires faiss" )(__UpperCamelCase )
      return test_case


def    a__       (						__UpperCamelCase ):
      try:
            import regex  # noqa
      except ImportError:
            SCREAMING_SNAKE_CASE_      =     unittest.skip("test requires regex" )(__UpperCamelCase )
      return test_case


def    a__       (						__UpperCamelCase ):
      try:
            import elasticsearch  # noqa
      except ImportError:
            SCREAMING_SNAKE_CASE_      =     unittest.skip("test requires elasticsearch" )(__UpperCamelCase )
      return test_case


def    a__       (						__UpperCamelCase ):
      try:
            import sqlalchemy  # noqa
      except ImportError:
            SCREAMING_SNAKE_CASE_      =     unittest.skip("test requires sqlalchemy" )(__UpperCamelCase )
      return test_case


def    a__       (						__UpperCamelCase ):
      if not config.TORCH_AVAILABLE:
            SCREAMING_SNAKE_CASE_      =     unittest.skip("test requires PyTorch" )(__UpperCamelCase )
      return test_case


def    a__       (						__UpperCamelCase ):
      if not config.TF_AVAILABLE:
            SCREAMING_SNAKE_CASE_      =     unittest.skip("test requires TensorFlow" )(__UpperCamelCase )
      return test_case


def    a__       (						__UpperCamelCase ):
      if not config.JAX_AVAILABLE:
            SCREAMING_SNAKE_CASE_      =     unittest.skip("test requires JAX" )(__UpperCamelCase )
      return test_case


def    a__       (						__UpperCamelCase ):
      if not config.PIL_AVAILABLE:
            SCREAMING_SNAKE_CASE_      =     unittest.skip("test requires Pillow" )(__UpperCamelCase )
      return test_case


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


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


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


def    a__       (						__UpperCamelCase ):

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

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

      return _require_spacy_model


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


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


def    a__       (						__UpperCamelCase ):
      if not _run_slow_tests or _run_slow_tests == 0:
            SCREAMING_SNAKE_CASE_      =     unittest.skip("test is slow" )(__UpperCamelCase )
      return test_case


def    a__       (						__UpperCamelCase ):
      if not _run_local_tests or _run_local_tests == 0:
            SCREAMING_SNAKE_CASE_      =     unittest.skip("test is local" )(__UpperCamelCase )
      return test_case


def    a__       (						__UpperCamelCase ):
      if not _run_packaged_tests or _run_packaged_tests == 0:
            SCREAMING_SNAKE_CASE_      =     unittest.skip("test is packaged" )(__UpperCamelCase )
      return test_case


def    a__       (						__UpperCamelCase ):
      if not _run_remote_tests or _run_remote_tests == 0:
            SCREAMING_SNAKE_CASE_      =     unittest.skip("test requires remote" )(__UpperCamelCase )
      return test_case


def    a__       (						*__UpperCamelCase ):
      def decorate(cls ):
            for name, fn in cls.__dict__.items():
                  if callable(__UpperCamelCase ) and name.startswith("test" ):
                        for decorator in decorators:
                              SCREAMING_SNAKE_CASE_      =     decorator(__UpperCamelCase )
                        setattr(cls   ,					__UpperCamelCase   ,					__UpperCamelCase )
            return cls

      return decorate


class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
  """simple docstring"""







  pass



class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
  """simple docstring"""







  lowerCamelCase__   =  0
  lowerCamelCase__   =  1
  lowerCamelCase__   =  2



@contextmanager
def    a__       (						__UpperCamelCase=OfflineSimulationMode.CONNECTION_FAILS   ,					__UpperCamelCase=1E-16 ):
      SCREAMING_SNAKE_CASE_      =     requests.Session().request

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

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

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


@contextmanager
def    a__       (						*__UpperCamelCase   ,					**__UpperCamelCase ):
      SCREAMING_SNAKE_CASE_      =     str(Path().resolve() )
      with tempfile.TemporaryDirectory(*__UpperCamelCase   ,					**__UpperCamelCase ) as tmp_dir:
            try:
                  os.chdir(__UpperCamelCase )
                  yield
            finally:
                  os.chdir(__UpperCamelCase )


@contextmanager
def    a__       (						):
      import gc

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


@contextmanager
def    a__       (						):
      import gc

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


def    a__       (						__UpperCamelCase   ,					__UpperCamelCase ):
      return deepcopy(__UpperCamelCase ).integers(0   ,					1_0_0   ,					1_0 ).tolist() == deepcopy(__UpperCamelCase ).integers(0   ,					1_0_0   ,					1_0 ).tolist()


def    a__       (						__UpperCamelCase ):
      import decorator
      from requests.exceptions import HTTPError

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

      return decorator.decorator(_wrapper   ,					__UpperCamelCase )


class      lowerCamelCase    :
  """simple docstring"""







  def __init__(							self       :				Optional[int]     ,   __magic_name__       :				str     ,   __magic_name__       :				Tuple     ,   __magic_name__       :				Union[str, Any]      )     ->		int:
        SCREAMING_SNAKE_CASE_      =     returncode
        SCREAMING_SNAKE_CASE_      =     stdout
        SCREAMING_SNAKE_CASE_      =     stderr



async def    a__       (						__UpperCamelCase   ,					__UpperCamelCase ):
      while True:
            SCREAMING_SNAKE_CASE_      =     await stream.readline()
            if line:
                  callback(__UpperCamelCase )
            else:
                  break


async def    a__       (						__UpperCamelCase   ,					__UpperCamelCase=None   ,					__UpperCamelCase=None   ,					__UpperCamelCase=None   ,					__UpperCamelCase=False   ,					__UpperCamelCase=False ):
      if echo:
            print("\nRunning: "   ,					" ".join(__UpperCamelCase ) )

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

      # 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)

      SCREAMING_SNAKE_CASE_      =     []
      SCREAMING_SNAKE_CASE_      =     []

      def tee(__UpperCamelCase   ,					__UpperCamelCase   ,					__UpperCamelCase   ,					__UpperCamelCase="" ):
            SCREAMING_SNAKE_CASE_      =     line.decode("utf-8" ).rstrip()
            sink.append(__UpperCamelCase )
            if not quiet:
                  print(__UpperCamelCase   ,					__UpperCamelCase   ,					file=__UpperCamelCase )

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


def    a__       (						__UpperCamelCase   ,					__UpperCamelCase=None   ,					__UpperCamelCase=None   ,					__UpperCamelCase=1_8_0   ,					__UpperCamelCase=False   ,					__UpperCamelCase=True ):
      SCREAMING_SNAKE_CASE_      =     asyncio.get_event_loop()
      SCREAMING_SNAKE_CASE_      =     loop.run_until_complete(
          _stream_subprocess(__UpperCamelCase   ,					env=__UpperCamelCase   ,					stdin=__UpperCamelCase   ,					timeout=__UpperCamelCase   ,					quiet=__UpperCamelCase   ,					echo=__UpperCamelCase ) )

      SCREAMING_SNAKE_CASE_      =     " ".join(__UpperCamelCase )
      if result.returncode > 0:
            SCREAMING_SNAKE_CASE_      =     "\n".join(result.stderr )
            raise RuntimeError(
                F'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n'''
                F'''The combined stderr from workers follows:\n{stderr}''' )

      # check that the subprocess actually did run and produced some output, should the test rely on
      # the remote side to do the testing
      if not result.stdout and not result.stderr:
            raise RuntimeError(F'''\'{cmd_str}\' produced no output.''' )

      return result


def    a__       (						):
      SCREAMING_SNAKE_CASE_      =     os.environ.get("PYTEST_XDIST_WORKER"   ,					"gw0" )
      SCREAMING_SNAKE_CASE_      =     re.sub(r"^gw"   ,					""   ,					__UpperCamelCase   ,					0   ,					re.M )
      return int(__UpperCamelCase )





def    a__       (						):
      SCREAMING_SNAKE_CASE_      =     2_9_5_0_0
      SCREAMING_SNAKE_CASE_      =     pytest_xdist_worker_id()
      return port + uniq_delta



import os
import unittest

from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer
from transformers.testing_utils import require_jieba, tooslow

from ...test_tokenization_common import TokenizerTesterMixin


@require_jieba
class      lowerCamelCase    (SCREAMING_SNAKE_CASE__     ,					unittest.TestCase    ):
  """simple docstring"""







  lowerCamelCase__   =  CpmAntTokenizer
  lowerCamelCase__   =  False







  def       __A   (							self       :				List[str]      )     ->		str:
        super().setUp()

        SCREAMING_SNAKE_CASE_      =     [
            "<d>",
            "</d>",
            "<s>",
            "</s>",
            "</_>",
            "<unk>",
            "<pad>",
            "</n>",
            "我",
            "是",
            "C",
            "P",
            "M",
            "A",
            "n",
            "t",
        ]
        SCREAMING_SNAKE_CASE_      =     os.path.join(self.tmpdirname     ,   VOCAB_FILES_NAMES["vocab_file"]      )
        with open(self.vocab_file     ,   "w"     ,   encoding="utf-8"      ) as vocab_writer:
              vocab_writer.write("".join([x + "\n" for x in vocab_tokens]      )      )







  @tooslow
  def       __A   (							self       :				int      )     ->		Union[str, Any]:
        SCREAMING_SNAKE_CASE_      =     CpmAntTokenizer.from_pretrained("openbmb/cpm-ant-10b"      )
        SCREAMING_SNAKE_CASE_      =     "今天天气真好！"
        SCREAMING_SNAKE_CASE_      =     ["今天", "天气", "真", "好", "！"]
        SCREAMING_SNAKE_CASE_      =     tokenizer.tokenize(__magic_name__      )
        self.assertListEqual(__magic_name__     ,   __magic_name__      )
        SCREAMING_SNAKE_CASE_      =     "今天天气真好！"
        SCREAMING_SNAKE_CASE_      =     [tokenizer.bos_token] + tokens

        SCREAMING_SNAKE_CASE_      =     [6, 9_802, 14_962, 2_082, 831, 244]
        self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__      )     ,   __magic_name__      )

        SCREAMING_SNAKE_CASE_      =     tokenizer.decode(__magic_name__      )
        self.assertEqual(__magic_name__     ,   __magic_name__      )


