
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    :    Dict       ,				__lowerCAmelCase    :    int=False							):




			"""simple docstring"""


			try:
						lowerCAmelCase_         =      os.environ[key]
			except KeyError:
						# KEY isn't set, default to `default`.
						lowerCAmelCase_         =      default
			else:
						# KEY is set, convert it to True or False.
						try:
									lowerCAmelCase_         =      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  =	parse_flag_from_env("RUN_SLOW", default=False)
_A  =	parse_flag_from_env("RUN_REMOTE", default=False)
_A  =	parse_flag_from_env("RUN_LOCAL", default=True)
_A  =	parse_flag_from_env("RUN_PACKAGED", default=True)

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

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

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






def   lowerCamelCase__							(							__lowerCAmelCase    :    List[str]							):




			"""simple docstring"""


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






def   lowerCamelCase__							(							__lowerCAmelCase    :    List[Any]							):




			"""simple docstring"""


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






def   lowerCamelCase__							(							__lowerCAmelCase    :    List[Any]							):




			"""simple docstring"""


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






def   lowerCamelCase__							(							__lowerCAmelCase    :    str							):




			"""simple docstring"""


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






def   lowerCamelCase__							(							__lowerCAmelCase    :    Union[str, Any]							):




			"""simple docstring"""


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






def   lowerCamelCase__							(							__lowerCAmelCase    :    Union[str, Any]							):




			"""simple docstring"""


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






def   lowerCamelCase__							(							__lowerCAmelCase    :    Optional[Any]							):




			"""simple docstring"""


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






def   lowerCamelCase__							(							__lowerCAmelCase    :    Optional[int]							):




			"""simple docstring"""


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






def   lowerCamelCase__							(							__lowerCAmelCase    :    Optional[int]							):




			"""simple docstring"""


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






def   lowerCamelCase__							(							__lowerCAmelCase    :    str							):




			"""simple docstring"""


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






def   lowerCamelCase__							(							__lowerCAmelCase    :    Tuple							):




			"""simple docstring"""


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






def   lowerCamelCase__							(							__lowerCAmelCase    :    Tuple							):




			"""simple docstring"""


			def _require_spacy_model(__lowerCAmelCase    :    Dict							):
						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   lowerCamelCase__							(							__lowerCAmelCase    :    int							):




			"""simple docstring"""


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






def   lowerCamelCase__							(							__lowerCAmelCase    :    List[Any]							):




			"""simple docstring"""


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






def   lowerCamelCase__							(							__lowerCAmelCase    :    str							):




			"""simple docstring"""


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






def   lowerCamelCase__							(							__lowerCAmelCase    :    Dict							):




			"""simple docstring"""


			if not _run_local_tests or _run_local_tests == 0:
						lowerCAmelCase_         =      unittest.skip("test is local"							)(UpperCamelCase__							)
			return test_case






def   lowerCamelCase__							(							__lowerCAmelCase    :    List[str]							):




			"""simple docstring"""


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






def   lowerCamelCase__							(							__lowerCAmelCase    :    Union[str, Any]							):




			"""simple docstring"""


			if not _run_remote_tests or _run_remote_tests == 0:
						lowerCAmelCase_         =      unittest.skip("test requires remote"							)(UpperCamelCase__							)
			return test_case






def   lowerCamelCase__							(							*__lowerCAmelCase    :    Union[str, Any]							):




			"""simple docstring"""


			def decorate(cls    :    Union[str, Any]							):
						for name, fn in cls.__dict__.items():
									if callable(UpperCamelCase__							) and name.startswith("test"							):
												for decorator in decorators:
															lowerCAmelCase_         =      decorator(UpperCamelCase__							)
												setattr(cls       ,				UpperCamelCase__       ,				UpperCamelCase__							)
						return cls

			return decorate





class       _lowerCAmelCase   (      UpperCAmelCase__			):
				pass





class       _lowerCAmelCase   (      UpperCAmelCase__			):
				_lowercase     						=0
				_lowercase     						=1
				_lowercase     						=2






@contextmanager
def   lowerCamelCase__							(							__lowerCAmelCase    :    str=OfflineSimulationMode.CONNECTION_FAILS       ,				__lowerCAmelCase    :    str=1e-16							):




			"""simple docstring"""


			lowerCAmelCase_         =      requests.Session().request

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

			def raise_connection_error(__lowerCAmelCase    :    str       ,				__lowerCAmelCase    :    str       ,				**__lowerCAmelCase    :    Any							):
						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   lowerCamelCase__							(							*__lowerCAmelCase    :    Union[str, Any]       ,				**__lowerCAmelCase    :    str							):




			"""simple docstring"""


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






@contextmanager
def   lowerCamelCase__							(							):




			"""simple docstring"""


			import gc

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






@contextmanager
def   lowerCamelCase__							(							):




			"""simple docstring"""


			import gc

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






def   lowerCamelCase__							(							__lowerCAmelCase    :    Optional[Any]       ,				__lowerCAmelCase    :    str							):




			"""simple docstring"""


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






def   lowerCamelCase__							(							__lowerCAmelCase    :    List[Any]							):




			"""simple docstring"""


			import decorator
			from requests.exceptions import HTTPError

			def _wrapper(__lowerCAmelCase    :    Any       ,				*__lowerCAmelCase    :    int       ,				**__lowerCAmelCase    :    List[Any]							):
						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   :




				def __init__(   self							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase	)							-> str:
							lowerCAmelCase_         =      returncode
							lowerCAmelCase_         =      stdout
							lowerCAmelCase_         =      stderr






async def   lowerCamelCase__							(							__lowerCAmelCase    :    List[str]       ,				__lowerCAmelCase    :    Dict							):




			"""simple docstring"""


			while True:
						lowerCAmelCase_         =      await stream.readline()
						if line:
									callback(UpperCamelCase__							)
						else:
									break






async def   lowerCamelCase__							(							__lowerCAmelCase    :    Dict       ,				__lowerCAmelCase    :    Optional[int]=None       ,				__lowerCAmelCase    :    Union[str, Any]=None       ,				__lowerCAmelCase    :    Optional[int]=None       ,				__lowerCAmelCase    :    Union[str, Any]=False       ,				__lowerCAmelCase    :    Union[str, Any]=False							):




			"""simple docstring"""


			if echo:
						print("\nRunning: "       ,				" ".join(UpperCamelCase__							)							)

			lowerCAmelCase_         =      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)

			lowerCAmelCase_         =      []
			lowerCAmelCase_         =      []

			def tee(__lowerCAmelCase    :    Union[str, Any]       ,				__lowerCAmelCase    :    Optional[Any]       ,				__lowerCAmelCase    :    List[Any]       ,				__lowerCAmelCase    :    List[str]=""							):
						lowerCAmelCase_         =      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 __lowerCAmelCase							: tee(UpperCamelCase__       ,				UpperCamelCase__       ,				sys.stdout       ,				label="stdout:"							)							),
			        _read_stream(p.stderr       ,				lambda __lowerCAmelCase							: tee(UpperCamelCase__       ,				UpperCamelCase__       ,				sys.stderr       ,				label="stderr:"							)							),
			    ]       ,				timeout=UpperCamelCase__       ,				)
			return _RunOutput(await p.wait()       ,				UpperCamelCase__       ,				UpperCamelCase__							)






def   lowerCamelCase__							(							__lowerCAmelCase    :    int       ,				__lowerCAmelCase    :    List[Any]=None       ,				__lowerCAmelCase    :    Union[str, Any]=None       ,				__lowerCAmelCase    :    str=180       ,				__lowerCAmelCase    :    List[str]=False       ,				__lowerCAmelCase    :    int=True							):




			"""simple docstring"""


			lowerCAmelCase_         =      asyncio.get_event_loop()
			lowerCAmelCase_         =      loop.run_until_complete(
			    _stream_subprocess(UpperCamelCase__       ,				env=UpperCamelCase__       ,				stdin=UpperCamelCase__       ,				timeout=UpperCamelCase__       ,				quiet=UpperCamelCase__       ,				echo=UpperCamelCase__							)							)

			lowerCAmelCase_         =      " ".join(UpperCamelCase__							)
			if result.returncode > 0:
						lowerCAmelCase_         =      "\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__							(							):




			"""simple docstring"""


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






def   lowerCamelCase__							(							):




			"""simple docstring"""


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




'''simple docstring'''




import json
import os
from typing import Optional, Tuple

import regex as re

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


__UpperCAmelCase					=logging.get_logger(__name__)

__UpperCAmelCase					={
    "vocab_file": "vocab.json",
    "merges_file": "merges.txt",
}

__UpperCAmelCase					={
    "vocab_file": {"ctrl": "https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json"},
    "merges_file": {"ctrl": "https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt"},
}

__UpperCAmelCase					={
    "ctrl": 2_5_6,
}

__UpperCAmelCase					={
    "Pregnancy": 1_6_8_6_2_9,
    "Christianity": 7_6_7_5,
    "Explain": 1_0_6_4_2_3,
    "Fitness": 6_3_4_4_0,
    "Saving": 6_3_1_6_3,
    "Ask": 2_7_1_7_1,
    "Ass": 9_5_9_8_5,
    "Joke": 1_6_3_5_0_9,
    "Questions": 4_5_6_2_2,
    "Thoughts": 4_9_6_0_5,
    "Retail": 5_2_3_4_2,
    "Feminism": 1_6_4_3_3_8,
    "Writing": 1_1_9_9_2,
    "Atheism": 1_9_2_2_6_3,
    "Netflix": 4_8_6_1_6,
    "Computing": 3_9_6_3_9,
    "Opinion": 4_3_2_1_3,
    "Alone": 4_4_9_6_7,
    "Funny": 5_8_9_1_7,
    "Gaming": 4_0_3_5_8,
    "Human": 4_0_8_8,
    "India": 1_3_3_1,
    "Joker": 7_7_1_3_8,
    "Diet": 3_6_2_0_6,
    "Legal": 1_1_8_5_9,
    "Norman": 4_9_3_9,
    "Tip": 7_2_6_8_9,
    "Weight": 5_2_3_4_3,
    "Movies": 4_6_2_7_3,
    "Running": 2_3_4_2_5,
    "Science": 2_0_9_0,
    "Horror": 3_7_7_9_3,
    "Confession": 6_0_5_7_2,
    "Finance": 1_2_2_5_0,
    "Politics": 1_6_3_6_0,
    "Scary": 1_9_1_9_8_5,
    "Support": 1_2_6_5_4,
    "Technologies": 3_2_5_1_6,
    "Teenage": 6_6_1_6_0,
    "Event": 3_2_7_6_9,
    "Learned": 6_7_4_6_0,
    "Notion": 1_8_2_7_7_0,
    "Wikipedia": 3_7_5_8_3,
    "Books": 6_6_6_5,
    "Extract": 7_6_0_5_0,
    "Confessions": 1_0_2_7_0_1,
    "Conspiracy": 7_5_9_3_2,
    "Links": 6_3_6_7_4,
    "Narcissus": 1_5_0_4_2_5,
    "Relationship": 5_4_7_6_6,
    "Relationships": 1_3_4_7_9_6,
    "Reviews": 4_1_6_7_1,
    "News": 4_2_5_6,
    "Translation": 2_6_8_2_0,
    "multilingual": 1_2_8_4_0_6,
}






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       Union[str, Any]:
    __lowerCamelCase            =    set()
    __lowerCamelCase            =    word[0]
    for char in word[1:]:
        pairs.add((prev_char, char)							)
        __lowerCamelCase            =    char

    __lowerCamelCase            =    set(UpperCamelCase__							)
    return pairs




class        a__ (  UpperCAmelCase__					):
     lowerCamelCase    :	str				=VOCAB_FILES_NAMES
     lowerCamelCase    :	Optional[int]				=PRETRAINED_VOCAB_FILES_MAP
     lowerCamelCase    :	Tuple				=PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     lowerCamelCase    :	Union[str, Any]				=CONTROL_CODES






     def __init__(					self						:						Optional[Any]    ,							a						:						str    ,							a						:						List[str]    ,							a						:						Optional[int]="<unk>"    ,							**a						:						Any       ):





         """simple docstring"""



         super().__init__(unk_token=a    ,							**a       )

         with open(a    ,							encoding='''utf-8'''       ) as vocab_handle:
             __lowerCamelCase            =    json.load(a       )
         __lowerCamelCase            =    {v: k for k, v in self.encoder.items()}
         with open(a    ,							encoding='''utf-8'''       ) as merges_handle:
             __lowerCamelCase            =    merges_handle.read().split('''\n'''       )[1:-1]
         __lowerCamelCase            =    [tuple(merge.split()       ) for merge in merges]
         __lowerCamelCase            =    dict(zip(a    ,							range(len(a       )       )       )       )
         __lowerCamelCase            =    {}






     @property
     def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[Any]       ):





         """simple docstring"""



         return len(self.encoder       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						int       ):





         """simple docstring"""



         return dict(self.encoder    ,							**self.added_tokens_encoder       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						List[Any]    ,							a						:						Dict       ):





         """simple docstring"""



         if token in self.cache:
             return self.cache[token]
         __lowerCamelCase            =    tuple(a       )
         __lowerCamelCase            =    tuple(list(word[:-1]       ) + [word[-1] + '''</w>''']       )
         __lowerCamelCase            =    get_pairs(a       )

         if not pairs:
             return token

         while True:
             __lowerCamelCase            =    min(a    ,							key=lambda a       : self.bpe_ranks.get(a    ,							float('''inf'''       )       )       )
             if bigram not in self.bpe_ranks:
                 break
             __lowerCamelCase      ,    __lowerCamelCase            =    bigram
             __lowerCamelCase            =    []
             __lowerCamelCase            =    0
             while i < len(a       ):
                 try:
                     __lowerCamelCase            =    word.index(a    ,							a       )
                 except ValueError:
                     new_word.extend(word[i:]       )
                     break
                 else:
                     new_word.extend(word[i:j]       )
                     __lowerCamelCase            =    j

                 if word[i] == first and i < len(a       ) - 1 and word[i + 1] == second:
                     new_word.append(first + second       )
                     i += 2
                 else:
                     new_word.append(word[i]       )
                     i += 1
             __lowerCamelCase            =    tuple(a       )
             __lowerCamelCase            =    new_word
             if len(a       ) == 1:
                 break
             else:
                 __lowerCamelCase            =    get_pairs(a       )
         __lowerCamelCase            =    '''@@ '''.join(a       )
         __lowerCamelCase            =    word[:-4]
         __lowerCamelCase            =    word
         return word






     def   SCREAMING_SNAKE_CASE__  (					self						:						str    ,							a						:						List[str]       ):





         """simple docstring"""



         __lowerCamelCase            =    []

         __lowerCamelCase            =    re.findall(R'''\S+\n?'''    ,							a       )

         for token in words:
             split_tokens.extend(list(self.bpe(a       ).split(''' '''       )       )       )
         return split_tokens






     def   SCREAMING_SNAKE_CASE__  (					self						:						Any    ,							a						:						Dict       ):





         """simple docstring"""



         return self.encoder.get(a    ,							self.encoder.get(self.unk_token       )       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						List[Any]    ,							a						:						Optional[Any]       ):





         """simple docstring"""



         return self.decoder.get(a    ,							self.unk_token       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[Any]    ,							a						:						Dict       ):





         """simple docstring"""



         __lowerCamelCase            =    ''' '''.join(a       ).replace('''@@ '''    ,							''''''       ).strip()
         return out_string






     def   SCREAMING_SNAKE_CASE__  (					self						:						List[Any]    ,							a						:						str    ,							a						:						Optional[str] = None       ):





         """simple docstring"""



         if not os.path.isdir(a       ):
             logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""       )
             return
         __lowerCamelCase            =    os.path.join(
             a    ,							(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']       )
         __lowerCamelCase            =    os.path.join(
             a    ,							(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file''']       )

         with open(a    ,							'''w'''    ,							encoding='''utf-8'''       ) as f:
             f.write(json.dumps(self.encoder    ,							indent=2    ,							sort_keys=a    ,							ensure_ascii=a       ) + '''\n'''       )

         __lowerCamelCase            =    0
         with open(a    ,							'''w'''    ,							encoding='''utf-8'''       ) as writer:
             writer.write('''#version: 0.2\n'''       )
             for bpe_tokens, token_index in sorted(self.bpe_ranks.items()    ,							key=lambda a       : kv[1]       ):
                 if index != token_index:
                     logger.warning(
                         f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."""
                         ''' Please check that the tokenizer is not corrupted!'''       )
                     __lowerCamelCase            =    token_index
                 writer.write(''' '''.join(a       ) + '''\n'''       )
                 index += 1

         return vocab_file, merge_file

     # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):
     #     filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens))
     #     tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens)
     #     tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far)
     #     return ''.join(tokens_generated_so_far)
