





"""simple docstring"""






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    (       SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE=False							)		->       str:






       """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(SCREAMING_SNAKE_CASE							)
              except ValueError:
                     # More values are supported, but let's keep the message simple.
                     raise ValueError(F"""If set, {key} must be yes or no."""							)
       return _value


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    (       SCREAMING_SNAKE_CASE							)		->       Optional[Any]:






       """simple docstring"""




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

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE							)		->       Union[str, Any]:






       """simple docstring"""




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

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE							)		->       List[Any]:






       """simple docstring"""




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

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE							)		->       Dict:






       """simple docstring"""




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

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE							)		->       str:






       """simple docstring"""




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

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE							)		->       List[Any]:






       """simple docstring"""




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

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE							)		->       List[Any]:






       """simple docstring"""




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

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE							)		->       str:






       """simple docstring"""




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

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE							)		->       int:






       """simple docstring"""




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

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE							)		->       int:






       """simple docstring"""




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

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE							)		->       Dict:






       """simple docstring"""




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

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE							)		->       str:






       """simple docstring"""




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

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

       return _require_spacy_model

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE							)		->       Optional[int]:






       """simple docstring"""




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

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE							)		->       Tuple:






       """simple docstring"""




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

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE							)		->       List[Any]:






       """simple docstring"""




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

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE							)		->       Union[str, Any]:






       """simple docstring"""




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

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE							)		->       Tuple:






       """simple docstring"""




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

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE							)		->       int:






       """simple docstring"""




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

def       __lowerCamelCase    (       *SCREAMING_SNAKE_CASE							)		->       List[str]:






       """simple docstring"""




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

       return decorate



class 	lowerCAmelCase					(      snake_case							):
       pass



class 	lowerCAmelCase					(      snake_case							):
       lowerCAmelCase__						 =  0
       lowerCAmelCase__						 =  1
       lowerCAmelCase__						 =  2


@contextmanager
def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE=OfflineSimulationMode.CONNECTION_FAILS,SCREAMING_SNAKE_CASE=1E-16							)		->       str:






       """simple docstring"""




       _UpperCAmelCase     =     requests.Session().request

       def timeout_request(SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE,**SCREAMING_SNAKE_CASE							):
              # 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(SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE,**SCREAMING_SNAKE_CASE							)
              except Exception as e:
                     # The following changes in the error are just here to make the offline timeout error prettier
                     _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(SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE,**SCREAMING_SNAKE_CASE							):
              raise requests.ConnectionError('Offline mode is enabled.',request=SCREAMING_SNAKE_CASE							)

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

@contextmanager
def       __lowerCamelCase    (       *SCREAMING_SNAKE_CASE,**SCREAMING_SNAKE_CASE							)		->       Any:






       """simple docstring"""




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

@contextmanager
def       __lowerCamelCase    (       )		->       List[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    (       )		->       Any:






       """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    (       SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE							)		->       Dict:






       """simple docstring"""




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

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE							)		->       List[str]:






       """simple docstring"""




       import decorator
       from requests.exceptions import HTTPError

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

       return decorator.decorator(_wrapper,SCREAMING_SNAKE_CASE							)



class 	lowerCAmelCase					:






       def __init__(   self    ,  a__    ,  a__    ,  a__     ):
              _UpperCAmelCase     =     returncode
              _UpperCAmelCase     =     stdout
              _UpperCAmelCase     =     stderr


async def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE							)		->       Any:






       """simple docstring"""




       while True:
              _UpperCAmelCase     =     await stream.readline()
              if line:
                     callback(SCREAMING_SNAKE_CASE							)
              else:
                     break

async def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE=None,SCREAMING_SNAKE_CASE=None,SCREAMING_SNAKE_CASE=None,SCREAMING_SNAKE_CASE=False,SCREAMING_SNAKE_CASE=False							)		->       _RunOutput:






       """simple docstring"""




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

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

       # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
       # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
       #
       # If it starts hanging, will need to switch to the following code. The problem is that no data
       # will be seen until it's done and if it hangs for example there will be no debug info.
       # out, err = await p.communicate()
       # return _RunOutput(p.returncode, out, err)

       _UpperCAmelCase     =     []
       _UpperCAmelCase     =     []

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

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

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE=None,SCREAMING_SNAKE_CASE=None,SCREAMING_SNAKE_CASE=180,SCREAMING_SNAKE_CASE=False,SCREAMING_SNAKE_CASE=True							)		->       _RunOutput:






       """simple docstring"""




       _UpperCAmelCase     =     asyncio.get_event_loop()
       _UpperCAmelCase     =     loop.run_until_complete(
           _stream_subprocess(SCREAMING_SNAKE_CASE,env=SCREAMING_SNAKE_CASE,stdin=SCREAMING_SNAKE_CASE,timeout=SCREAMING_SNAKE_CASE,quiet=SCREAMING_SNAKE_CASE,echo=SCREAMING_SNAKE_CASE							)							)

       _UpperCAmelCase     =     ' '.join(SCREAMING_SNAKE_CASE							)
       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    (       )		->       Optional[int]:






       """simple docstring"""




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


def       __lowerCamelCase    (       )		->       int:






       """simple docstring"""




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













"""simple docstring"""






import unittest

from transformers import RoFormerTokenizer, RoFormerTokenizerFast
from transformers.testing_utils import require_rjieba, require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin



@require_rjieba
@require_tokenizers
class 	lowerCAmelCase					(      snake_case			,	unittest.TestCase							):
       lowerCAmelCase__						 =  RoFormerTokenizer
       lowerCAmelCase__						 =  RoFormerTokenizerFast
       lowerCAmelCase__						 =  True
       lowerCAmelCase__						 =  True






       def 							__A (   self     ):
              super().setUp()






       def 							__A (   self    ,  **a__     ):
              return self.tokenizer_class.from_pretrained('junnyu/roformer_chinese_base'    ,  **a__     )






       def 							__A (   self    ,  **a__     ):
              return self.rust_tokenizer_class.from_pretrained('junnyu/roformer_chinese_base'    ,  **a__     )






       def 							__A (   self     ):
              _UpperCAmelCase     =     '永和服装饰品有限公司,今天天气非常好'
              _UpperCAmelCase     =     '永和 服装 饰品 有限公司 , 今 天 天 气 非常 好'
              return input_text, output_text






       def 							__A (   self     ):
              _UpperCAmelCase     =     self.get_tokenizer()
              _UpperCAmelCase    ,							_UpperCAmelCase     =     self.get_chinese_input_output_texts()
              _UpperCAmelCase     =     tokenizer.tokenize(a__     )

              self.assertListEqual(a__    ,  output_text.split()     )

              _UpperCAmelCase     =     tokens + [tokenizer.unk_token]
              _UpperCAmelCase     =     [2_29_43, 2_13_32, 3_44_31, 4_59_04, 1_17, 3_06, 12_31, 12_31, 26_53, 3_39_94, 12_66, 1_00]
              self.assertListEqual(tokenizer.convert_tokens_to_ids(a__     )    ,  a__     )






       def 							__A (   self     ):
              _UpperCAmelCase     =     self.get_rust_tokenizer()
              _UpperCAmelCase    ,							_UpperCAmelCase     =     self.get_chinese_input_output_texts()
              _UpperCAmelCase     =     tokenizer.tokenize(a__     )
              self.assertListEqual(a__    ,  output_text.split()     )
              _UpperCAmelCase     =     tokens + [tokenizer.unk_token]
              _UpperCAmelCase     =     [2_29_43, 2_13_32, 3_44_31, 4_59_04, 1_17, 3_06, 12_31, 12_31, 26_53, 3_39_94, 12_66, 1_00]
              self.assertListEqual(tokenizer.convert_tokens_to_ids(a__     )    ,  a__     )






       def 							__A (   self     ):
              pass






       def 							__A (   self     ):
              pass






       def 							__A (   self     ):
              pass






