'''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 _lowercase	(      lowerCamelCase__							,    lowerCamelCase__=False						)					->       Dict:





       """simple docstring"""


       try:
              __UpperCAmelCase  :				str       				=		os.environ[key]
       except KeyError:
              # KEY isn't set, default to `default`.
              __UpperCAmelCase  :				List[str]       				=		default
       else:
              # KEY is set, convert it to True or False.
              try:
                     __UpperCAmelCase  :				int       				=		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


_a   :	Any 							=   parse_flag_from_env("RUN_SLOW", default=False)
_a   :	str 							=   parse_flag_from_env("RUN_REMOTE", default=False)
_a   :	Any 							=   parse_flag_from_env("RUN_LOCAL", default=True)
_a   :	Union[str, Any] 							=   parse_flag_from_env("RUN_PACKAGED", default=True)

# Compression
_a   :	Any 							=   pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="test requires lz4")
_a   :	Union[str, Any] 							=   pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="test requires py7zr")
_a   :	List[str] 							=   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   :	Tuple 							=   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   :	int 							=   pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("0.3.2"),
    reason="test requires dill>0.3.2 for cloudpickle compatibility",
)

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

def _lowercase	(      lowerCamelCase__						)					->       Any:





       """simple docstring"""


       try:
              import faiss  # noqa
       except ImportError:
              __UpperCAmelCase  :				List[str]       				=		unittest.skip("test requires faiss"						)(lowerCamelCase__						)
       return test_case

def _lowercase	(      lowerCamelCase__						)					->       List[Any]:





       """simple docstring"""


       try:
              import regex  # noqa
       except ImportError:
              __UpperCAmelCase  :				Tuple       				=		unittest.skip("test requires regex"						)(lowerCamelCase__						)
       return test_case

def _lowercase	(      lowerCamelCase__						)					->       List[str]:





       """simple docstring"""


       try:
              import elasticsearch  # noqa
       except ImportError:
              __UpperCAmelCase  :				List[str]       				=		unittest.skip("test requires elasticsearch"						)(lowerCamelCase__						)
       return test_case

def _lowercase	(      lowerCamelCase__						)					->       Optional[Any]:





       """simple docstring"""


       try:
              import sqlalchemy  # noqa
       except ImportError:
              __UpperCAmelCase  :				Any       				=		unittest.skip("test requires sqlalchemy"						)(lowerCamelCase__						)
       return test_case

def _lowercase	(      lowerCamelCase__						)					->       int:





       """simple docstring"""


       if not config.TORCH_AVAILABLE:
              __UpperCAmelCase  :				int       				=		unittest.skip("test requires PyTorch"						)(lowerCamelCase__						)
       return test_case

def _lowercase	(      lowerCamelCase__						)					->       Dict:





       """simple docstring"""


       if not config.TF_AVAILABLE:
              __UpperCAmelCase  :				List[str]       				=		unittest.skip("test requires TensorFlow"						)(lowerCamelCase__						)
       return test_case

def _lowercase	(      lowerCamelCase__						)					->       int:





       """simple docstring"""


       if not config.JAX_AVAILABLE:
              __UpperCAmelCase  :				str       				=		unittest.skip("test requires JAX"						)(lowerCamelCase__						)
       return test_case

def _lowercase	(      lowerCamelCase__						)					->       List[Any]:





       """simple docstring"""


       if not config.PIL_AVAILABLE:
              __UpperCAmelCase  :				Union[str, Any]       				=		unittest.skip("test requires Pillow"						)(lowerCamelCase__						)
       return test_case

def _lowercase	(      lowerCamelCase__						)					->       Tuple:





       """simple docstring"""


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

def _lowercase	(      lowerCamelCase__						)					->       int:





       """simple docstring"""


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

def _lowercase	(      lowerCamelCase__						)					->       Union[str, Any]:





       """simple docstring"""


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

def _lowercase	(      lowerCamelCase__						)					->       Any:





       """simple docstring"""


       def _require_spacy_model(lowerCamelCase__						):
              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 _lowercase	(      lowerCamelCase__						)					->       Optional[Any]:





       """simple docstring"""


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

def _lowercase	(      lowerCamelCase__						)					->       Optional[Any]:





       """simple docstring"""


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

def _lowercase	(      lowerCamelCase__						)					->       Tuple:





       """simple docstring"""


       if not _run_slow_tests or _run_slow_tests == 0:
              __UpperCAmelCase  :				int       				=		unittest.skip("test is slow"						)(lowerCamelCase__						)
       return test_case

def _lowercase	(      lowerCamelCase__						)					->       str:





       """simple docstring"""


       if not _run_local_tests or _run_local_tests == 0:
              __UpperCAmelCase  :				List[str]       				=		unittest.skip("test is local"						)(lowerCamelCase__						)
       return test_case

def _lowercase	(      lowerCamelCase__						)					->       Dict:





       """simple docstring"""


       if not _run_packaged_tests or _run_packaged_tests == 0:
              __UpperCAmelCase  :				Tuple       				=		unittest.skip("test is packaged"						)(lowerCamelCase__						)
       return test_case

def _lowercase	(      lowerCamelCase__						)					->       Any:





       """simple docstring"""


       if not _run_remote_tests or _run_remote_tests == 0:
              __UpperCAmelCase  :				Any       				=		unittest.skip("test requires remote"						)(lowerCamelCase__						)
       return test_case

def _lowercase	(      *lowerCamelCase__						)					->       Tuple:





       """simple docstring"""


       def decorate(cls						):
              for name, fn in cls.__dict__.items():
                     if callable(lowerCamelCase__						) and name.startswith("test"						):
                            for decorator in decorators:
                                   __UpperCAmelCase  :				Tuple       				=		decorator(lowerCamelCase__						)
                            setattr(cls							,    lowerCamelCase__							,    lowerCamelCase__						)
              return cls

       return decorate






class 		__A       (__magic_name__   ):
       pass






class 		__A       (__magic_name__   ):
       snake_case       :List[str]				    =					0
       snake_case       :Any				    =					1
       snake_case       :Dict				    =					2





@contextmanager
def _lowercase	(      lowerCamelCase__=OfflineSimulationMode.CONNECTION_FAILS							,    lowerCamelCase__=1e-1_6						)					->       int:





       """simple docstring"""


       __UpperCAmelCase  :				Optional[Any]       				=		requests.Session().request

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

       def raise_connection_error(lowerCamelCase__							,    lowerCamelCase__							,    **lowerCamelCase__						):
              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 _lowercase	(      *lowerCamelCase__							,    **lowerCamelCase__						)					->       str:





       """simple docstring"""


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

@contextmanager
def _lowercase	(      )					->       Any:





       """simple docstring"""


       import gc

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

@contextmanager
def _lowercase	(      )					->       List[Any]:





       """simple docstring"""


       import gc

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

def _lowercase	(      lowerCamelCase__							,    lowerCamelCase__						)					->       str:





       """simple docstring"""


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

def _lowercase	(      lowerCamelCase__						)					->       int:





       """simple docstring"""


       import decorator
       from requests.exceptions import HTTPError

       def _wrapper(lowerCamelCase__							,    *lowerCamelCase__							,    **lowerCamelCase__						):
              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 		__A       :






       def __init__(      self				,     UpperCamelCase_				,     UpperCamelCase_				,     UpperCamelCase_      ):
              __UpperCAmelCase  :				Optional[Any]       				=		returncode
              __UpperCAmelCase  :				Optional[int]       				=		stdout
              __UpperCAmelCase  :				int       				=		stderr





async def _lowercase	(      lowerCamelCase__							,    lowerCamelCase__						)					->       Union[str, Any]:





       """simple docstring"""


       while True:
              __UpperCAmelCase  :				Any       				=		await stream.readline()
              if line:
                     callback(lowerCamelCase__						)
              else:
                     break

async def _lowercase	(      lowerCamelCase__							,    lowerCamelCase__=None							,    lowerCamelCase__=None							,    lowerCamelCase__=None							,    lowerCamelCase__=False							,    lowerCamelCase__=False						)					->       _RunOutput:





       """simple docstring"""


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

       __UpperCAmelCase  :				Optional[Any]       				=		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)

       __UpperCAmelCase  :				Union[str, Any]       				=		[]
       __UpperCAmelCase  :				Tuple       				=		[]

       def tee(lowerCamelCase__							,    lowerCamelCase__							,    lowerCamelCase__							,    lowerCamelCase__=""						):
              __UpperCAmelCase  :				List[Any]       				=		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 _lowercase	(      lowerCamelCase__							,    lowerCamelCase__=None							,    lowerCamelCase__=None							,    lowerCamelCase__=180							,    lowerCamelCase__=False							,    lowerCamelCase__=True						)					->       _RunOutput:





       """simple docstring"""


       __UpperCAmelCase  :				Dict       				=		asyncio.get_event_loop()
       __UpperCAmelCase  :				int       				=		loop.run_until_complete(
           _stream_subprocess(lowerCamelCase__							,    env=lowerCamelCase__							,    stdin=lowerCamelCase__							,    timeout=lowerCamelCase__							,    quiet=lowerCamelCase__							,    echo=lowerCamelCase__						)						)

       __UpperCAmelCase  :				List[Any]       				=		" ".join(lowerCamelCase__						)
       if result.returncode > 0:
              __UpperCAmelCase  :				Dict       				=		"\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 _lowercase	(      )					->       str:





       """simple docstring"""


       __UpperCAmelCase  :				Tuple       				=		os.environ.get("PYTEST_XDIST_WORKER"							,    "gw0"						)
       __UpperCAmelCase  :				Tuple       				=		re.sub(R"^gw"							,    ""							,    lowerCamelCase__							,    0							,    re.M						)
       return int(lowerCamelCase__						)


def _lowercase	(      )					->       Optional[Any]:





       """simple docstring"""


       __UpperCAmelCase  :				Dict       				=		2_9500
       __UpperCAmelCase  :				Any       				=		pytest_xdist_worker_id()
       return port + uniq_delta







'''simple docstring'''




import json
import os
from functools import lru_cache
from typing import List, Optional, Tuple

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


_a   :	Optional[Any] 							=   logging.get_logger(__name__)


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

# See all BART models at https://huggingface.co/models?filter=bart
_a   :	Tuple 							=   {
    "vocab_file": {
        "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json",
        "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json",
        "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json",
        "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json",
        "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json",
        "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json",
    },
    "merges_file": {
        "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt",
        "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt",
        "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt",
        "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt",
        "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt",
        "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt",
    },
}

_a   :	List[Any] 							=   {
    "facebook/bart-base": 1024,
    "facebook/bart-large": 1024,
    "facebook/bart-large-mnli": 1024,
    "facebook/bart-large-cnn": 1024,
    "facebook/bart-large-xsum": 1024,
    "yjernite/bart_eli5": 1024,
}

@lru_cache()
def _lowercase	(      )					->       List[Any]:





       """simple docstring"""


       __UpperCAmelCase  :				Dict       				=		(
           list(range(ord("!"						)							,    ord("~"						) + 1						)						) + list(range(ord("¡"						)							,    ord("¬"						) + 1						)						) + list(range(ord("®"						)							,    ord("ÿ"						) + 1						)						)
       )
       __UpperCAmelCase  :				Optional[Any]       				=		bs[:]
       __UpperCAmelCase  :				Optional[int]       				=		0
       for b in range(2**8						):
              if b not in bs:
                     bs.append(lowerCamelCase__						)
                     cs.append(2**8 + n						)
                     n += 1
       __UpperCAmelCase  :				Dict       				=		[chr(lowerCamelCase__						) for n in cs]
       return dict(zip(lowerCamelCase__							,    lowerCamelCase__						)						)

def _lowercase	(      lowerCamelCase__						)					->       str:





       """simple docstring"""


       __UpperCAmelCase  :				Dict       				=		set()
       __UpperCAmelCase  :				Union[str, Any]       				=		word[0]
       for char in word[1:]:
              pairs.add((prev_char, char)						)
              __UpperCAmelCase  :				Optional[Any]       				=		char
       return pairs






class 		__A       (__magic_name__   ):
       snake_case       :Optional[int]				    =					VOCAB_FILES_NAMES
       snake_case       :List[Any]				    =					PRETRAINED_VOCAB_FILES_MAP
       snake_case       :Any				    =					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       snake_case       :Optional[int]				    =					["input_ids", "attention_mask"]






       def __init__(      self				,     UpperCamelCase_				,     UpperCamelCase_				,     UpperCamelCase_="replace"				,     UpperCamelCase_="<s>"				,     UpperCamelCase_="</s>"				,     UpperCamelCase_="</s>"				,     UpperCamelCase_="<s>"				,     UpperCamelCase_="<unk>"				,     UpperCamelCase_="<pad>"				,     UpperCamelCase_="<mask>"				,     UpperCamelCase_=False				,     **UpperCamelCase_				,     ):
              __UpperCAmelCase  :				str       				=		AddedToken(UpperCamelCase_				,     lstrip=UpperCamelCase_				,     rstrip=UpperCamelCase_      ) if isinstance(UpperCamelCase_				,     UpperCamelCase_      ) else bos_token
              __UpperCAmelCase  :				List[str]       				=		AddedToken(UpperCamelCase_				,     lstrip=UpperCamelCase_				,     rstrip=UpperCamelCase_      ) if isinstance(UpperCamelCase_				,     UpperCamelCase_      ) else eos_token
              __UpperCAmelCase  :				Optional[int]       				=		AddedToken(UpperCamelCase_				,     lstrip=UpperCamelCase_				,     rstrip=UpperCamelCase_      ) if isinstance(UpperCamelCase_				,     UpperCamelCase_      ) else sep_token
              __UpperCAmelCase  :				int       				=		AddedToken(UpperCamelCase_				,     lstrip=UpperCamelCase_				,     rstrip=UpperCamelCase_      ) if isinstance(UpperCamelCase_				,     UpperCamelCase_      ) else cls_token
              __UpperCAmelCase  :				Optional[int]       				=		AddedToken(UpperCamelCase_				,     lstrip=UpperCamelCase_				,     rstrip=UpperCamelCase_      ) if isinstance(UpperCamelCase_				,     UpperCamelCase_      ) else unk_token
              __UpperCAmelCase  :				Dict       				=		AddedToken(UpperCamelCase_				,     lstrip=UpperCamelCase_				,     rstrip=UpperCamelCase_      ) if isinstance(UpperCamelCase_				,     UpperCamelCase_      ) else pad_token

              # Mask token behave like a normal word, i.e. include the space before it
              __UpperCAmelCase  :				Union[str, Any]       				=		AddedToken(UpperCamelCase_				,     lstrip=UpperCamelCase_				,     rstrip=UpperCamelCase_      ) if isinstance(UpperCamelCase_				,     UpperCamelCase_      ) else mask_token

              super().__init__(
                  errors=UpperCamelCase_				,     bos_token=UpperCamelCase_				,     eos_token=UpperCamelCase_				,     unk_token=UpperCamelCase_				,     sep_token=UpperCamelCase_				,     cls_token=UpperCamelCase_				,     pad_token=UpperCamelCase_				,     mask_token=UpperCamelCase_				,     add_prefix_space=UpperCamelCase_				,     **UpperCamelCase_				,     )

              with open(UpperCamelCase_				,     encoding="utf-8"      ) as vocab_handle:
                     __UpperCAmelCase  :				int       				=		json.load(UpperCamelCase_      )
              __UpperCAmelCase  :				Any       				=		{v: k for k, v in self.encoder.items()}
              __UpperCAmelCase  :				Any       				=		errors  # how to handle errors in decoding
              __UpperCAmelCase  :				str       				=		bytes_to_unicode()
              __UpperCAmelCase  :				List[str]       				=		{v: k for k, v in self.byte_encoder.items()}
              with open(UpperCamelCase_				,     encoding="utf-8"      ) as merges_handle:
                     __UpperCAmelCase  :				str       				=		merges_handle.read().split("\n"      )[1:-1]
              __UpperCAmelCase  :				List[str]       				=		[tuple(merge.split()      ) for merge in bpe_merges]
              __UpperCAmelCase  :				Union[str, Any]       				=		dict(zip(UpperCamelCase_				,     range(len(UpperCamelCase_      )      )      )      )
              __UpperCAmelCase  :				Optional[int]       				=		{}
              __UpperCAmelCase  :				Optional[int]       				=		add_prefix_space

              # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
              __UpperCAmelCase  :				Dict       				=		re.compile(r"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+"      )






       @property
       def 			_snake_case						(      self      ):
              return len(self.encoder      )






       def 			_snake_case						(      self      ):
              return dict(self.encoder				,     **self.added_tokens_encoder      )






       def 			_snake_case						(      self				,     UpperCamelCase_      ):
              if token in self.cache:
                     return self.cache[token]
              __UpperCAmelCase  :				List[str]       				=		tuple(UpperCamelCase_      )
              __UpperCAmelCase  :				str       				=		get_pairs(UpperCamelCase_      )

              if not pairs:
                     return token

              while True:
                     __UpperCAmelCase  :				str       				=		min(UpperCamelCase_				,     key=lambda UpperCamelCase_      : self.bpe_ranks.get(UpperCamelCase_				,     float("inf"      )      )      )
                     if bigram not in self.bpe_ranks:
                            break
                     __UpperCAmelCase				, __UpperCAmelCase  :				List[Any]       				=		bigram
                     __UpperCAmelCase  :				Any       				=		[]
                     __UpperCAmelCase  :				List[str]       				=		0
                     while i < len(UpperCamelCase_      ):
                            try:
                                   __UpperCAmelCase  :				Union[str, Any]       				=		word.index(UpperCamelCase_				,     UpperCamelCase_      )
                            except ValueError:
                                   new_word.extend(word[i:]      )
                                   break
                            else:
                                   new_word.extend(word[i:j]      )
                                   __UpperCAmelCase  :				str       				=		j

                            if word[i] == first and i < len(UpperCamelCase_      ) - 1 and word[i + 1] == second:
                                   new_word.append(first + second      )
                                   i += 2
                            else:
                                   new_word.append(word[i]      )
                                   i += 1
                     __UpperCAmelCase  :				Dict       				=		tuple(UpperCamelCase_      )
                     __UpperCAmelCase  :				str       				=		new_word
                     if len(UpperCamelCase_      ) == 1:
                            break
                     else:
                            __UpperCAmelCase  :				int       				=		get_pairs(UpperCamelCase_      )
              __UpperCAmelCase  :				Optional[int]       				=		" ".join(UpperCamelCase_      )
              __UpperCAmelCase  :				Dict       				=		word
              return word






       def 			_snake_case						(      self				,     UpperCamelCase_      ):
              __UpperCAmelCase  :				Optional[Any]       				=		[]
              for token in re.findall(self.pat				,     UpperCamelCase_      ):
                     __UpperCAmelCase  :				Any       				=		"".join(
                         self.byte_encoder[b] for b in token.encode("utf-8"      )      )  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
                     bpe_tokens.extend(bpe_token for bpe_token in self.bpe(UpperCamelCase_      ).split(" "      )      )
              return bpe_tokens






       def 			_snake_case						(      self				,     UpperCamelCase_      ):
              return self.encoder.get(UpperCamelCase_				,     self.encoder.get(self.unk_token      )      )






       def 			_snake_case						(      self				,     UpperCamelCase_      ):
              return self.decoder.get(UpperCamelCase_      )






       def 			_snake_case						(      self				,     UpperCamelCase_      ):
              __UpperCAmelCase  :				List[str]       				=		"".join(UpperCamelCase_      )
              __UpperCAmelCase  :				Union[str, Any]       				=		bytearray([self.byte_decoder[c] for c in text]      ).decode("utf-8"				,     errors=self.errors      )
              return text






       def 			_snake_case						(      self				,     UpperCamelCase_				,     UpperCamelCase_ = None      ):
              if not os.path.isdir(UpperCamelCase_      ):
                     logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""      )
                     return
              __UpperCAmelCase  :				Any       				=		os.path.join(
                  UpperCamelCase_				,     (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]      )
              __UpperCAmelCase  :				Optional[int]       				=		os.path.join(
                  UpperCamelCase_				,     (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]      )

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

              __UpperCAmelCase  :				str       				=		0
              with open(UpperCamelCase_				,     "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 UpperCamelCase_      : 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!"      )
                                   __UpperCAmelCase  :				str       				=		token_index
                            writer.write(" ".join(UpperCamelCase_      ) + "\n"      )
                            index += 1

              return vocab_file, merge_file






       def 			_snake_case						(      self				,     UpperCamelCase_				,     UpperCamelCase_ = None      ):
              if token_ids_a is None:
                     return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
              __UpperCAmelCase  :				List[Any]       				=		[self.cls_token_id]
              __UpperCAmelCase  :				Tuple       				=		[self.sep_token_id]
              return cls + token_ids_a + sep + sep + token_ids_a + sep






       def 			_snake_case						(      self				,     UpperCamelCase_				,     UpperCamelCase_ = None				,     UpperCamelCase_ = False      ):
              if already_has_special_tokens:
                     return super().get_special_tokens_mask(
                         token_ids_a=UpperCamelCase_				,     token_ids_a=UpperCamelCase_				,     already_has_special_tokens=UpperCamelCase_      )

              if token_ids_a is None:
                     return [1] + ([0] * len(UpperCamelCase_      )) + [1]
              return [1] + ([0] * len(UpperCamelCase_      )) + [1, 1] + ([0] * len(UpperCamelCase_      )) + [1]






       def 			_snake_case						(      self				,     UpperCamelCase_				,     UpperCamelCase_ = None      ):
              __UpperCAmelCase  :				int       				=		[self.sep_token_id]
              __UpperCAmelCase  :				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 + sep + token_ids_a + sep      ) * [0]







       def 			_snake_case						(      self				,     UpperCamelCase_				,     UpperCamelCase_=False				,     **UpperCamelCase_      ):
              __UpperCAmelCase  :				List[str]       				=		kwargs.pop("add_prefix_space"				,     self.add_prefix_space      )
              if (is_split_into_words or add_prefix_space) and (len(UpperCamelCase_      ) > 0 and not text[0].isspace()):
                     __UpperCAmelCase  :				Tuple       				=		" " + text
              return (text, kwargs)






