
'''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  __snake_case     (    _UpperCAmelCase					:       Tuple,      _UpperCAmelCase					:       Optional[int]=False):
   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(_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


snake_case_ :  str     =					parse_flag_from_env('RUN_SLOW', default=False)
snake_case_ :  List[str]     =					parse_flag_from_env('RUN_REMOTE', default=False)
snake_case_ :  Any     =					parse_flag_from_env('RUN_LOCAL', default=True)
snake_case_ :  Union[str, Any]     =					parse_flag_from_env('RUN_PACKAGED', default=True)

# Compression
snake_case_ :  Union[str, Any]     =					pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4')
snake_case_ :  Union[str, Any]     =					pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr')
snake_case_ :  Tuple     =					pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard')

# Audio
snake_case_ :  Optional[int]     =					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
snake_case_ :  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
snake_case_ :  Dict     =					pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('0.3.2'),
    reason='test requires dill>0.3.2 for cloudpickle compatibility',
)

# Windows
snake_case_ :  List[str]     =					pytest.mark.skipif(
    sys.platform == 'win32',
    reason='test should not be run on Windows',
)



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



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



def  __snake_case     (    _UpperCAmelCase					:       List[str]):
   try:
      import elasticsearch  # noqa
   except ImportError:
      UpperCamelCase       =  unittest.skip('''test requires elasticsearch''')(_UpperCAmelCase)
   return test_case



def  __snake_case     (    _UpperCAmelCase					:       List[Any]):
   try:
      import sqlalchemy  # noqa
   except ImportError:
      UpperCamelCase       =  unittest.skip('''test requires sqlalchemy''')(_UpperCAmelCase)
   return test_case



def  __snake_case     (    _UpperCAmelCase					:       Optional[Any]):
   if not config.TORCH_AVAILABLE:
      UpperCamelCase       =  unittest.skip('''test requires PyTorch''')(_UpperCAmelCase)
   return test_case



def  __snake_case     (    _UpperCAmelCase					:       Optional[int]):
   if not config.TF_AVAILABLE:
      UpperCamelCase       =  unittest.skip('''test requires TensorFlow''')(_UpperCAmelCase)
   return test_case



def  __snake_case     (    _UpperCAmelCase					:       Dict):
   if not config.JAX_AVAILABLE:
      UpperCamelCase       =  unittest.skip('''test requires JAX''')(_UpperCAmelCase)
   return test_case



def  __snake_case     (    _UpperCAmelCase					:       List[str]):
   if not config.PIL_AVAILABLE:
      UpperCamelCase       =  unittest.skip('''test requires Pillow''')(_UpperCAmelCase)
   return test_case



def  __snake_case     (    _UpperCAmelCase					:       Optional[int]):
   try:
      import transformers  # noqa F401
   except ImportError:
      return unittest.skip('''test requires transformers''')(_UpperCAmelCase)
   else:
      return test_case



def  __snake_case     (    _UpperCAmelCase					:       List[Any]):
   try:
      import tiktoken  # noqa F401
   except ImportError:
      return unittest.skip('''test requires tiktoken''')(_UpperCAmelCase)
   else:
      return test_case



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



def  __snake_case     (    _UpperCAmelCase					:       Dict):

   def _require_spacy_model(_UpperCAmelCase					:       List[Any]):
      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  __snake_case     (    _UpperCAmelCase					:       List[Any]):
   try:
      import pyspark  # noqa F401
   except ImportError:
      return unittest.skip('''test requires pyspark''')(_UpperCAmelCase)
   else:
      return test_case



def  __snake_case     (    _UpperCAmelCase					:       Optional[int]):
   try:
      import joblibspark  # noqa F401
   except ImportError:
      return unittest.skip('''test requires joblibspark''')(_UpperCAmelCase)
   else:
      return test_case



def  __snake_case     (    _UpperCAmelCase					:       str):
   if not _run_slow_tests or _run_slow_tests == 0:
      UpperCamelCase       =  unittest.skip('''test is slow''')(_UpperCAmelCase)
   return test_case



def  __snake_case     (    _UpperCAmelCase					:       Dict):
   if not _run_local_tests or _run_local_tests == 0:
      UpperCamelCase       =  unittest.skip('''test is local''')(_UpperCAmelCase)
   return test_case



def  __snake_case     (    _UpperCAmelCase					:       Union[str, Any]):
   if not _run_packaged_tests or _run_packaged_tests == 0:
      UpperCamelCase       =  unittest.skip('''test is packaged''')(_UpperCAmelCase)
   return test_case



def  __snake_case     (    _UpperCAmelCase					:       Optional[int]):
   if not _run_remote_tests or _run_remote_tests == 0:
      UpperCamelCase       =  unittest.skip('''test requires remote''')(_UpperCAmelCase)
   return test_case



def  __snake_case     (    *_UpperCAmelCase					:       Union[str, Any]):
   def decorate(cls					:       Any):
      for name, fn in cls.__dict__.items():
         if callable(_UpperCAmelCase) and name.startswith('''test'''):
            for decorator in decorators:
               UpperCamelCase       =  decorator(_UpperCAmelCase)
            setattr(cls,      _UpperCAmelCase,      _UpperCAmelCase)
      return cls

   return decorate


class 						lowercase__	(  snake_case_   ):






   '''simple docstring'''







   pass




class 						lowercase__	(  snake_case_   ):






   '''simple docstring'''







   _snake_case		   =							0
   _snake_case		   =							1
   _snake_case		   =							2




@contextmanager
def  __snake_case     (    _UpperCAmelCase					:       List[Any]=OfflineSimulationMode.CONNECTION_FAILS,      _UpperCAmelCase					:       Union[str, Any]=1E-1_6):
   UpperCamelCase       =  requests.Session().request

   def timeout_request(_UpperCAmelCase					:       Optional[int],      _UpperCAmelCase					:       str,      _UpperCAmelCase					:       Dict,      **_UpperCAmelCase					:       Tuple):
      # 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(_UpperCAmelCase,      _UpperCAmelCase,      **_UpperCAmelCase)
      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(_UpperCAmelCase					:       Optional[int],      _UpperCAmelCase					:       Union[str, Any],      **_UpperCAmelCase					:       Union[str, 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  __snake_case     (    *_UpperCAmelCase					:       Any,      **_UpperCAmelCase					:       Dict):
   UpperCamelCase       =  str(Path().resolve())
   with tempfile.TemporaryDirectory(*_UpperCAmelCase,      **_UpperCAmelCase) as tmp_dir:
      try:
         os.chdir(_UpperCAmelCase)
         yield
      finally:
         os.chdir(_UpperCAmelCase)



@contextmanager
def  __snake_case     (    ):
   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  __snake_case     (    ):
   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  __snake_case     (    _UpperCAmelCase					:       List[Any],      _UpperCAmelCase					:       str):
   return deepcopy(_UpperCAmelCase).integers(0,      100,      10).tolist() == deepcopy(_UpperCAmelCase).integers(0,      100,      10).tolist()



def  __snake_case     (    _UpperCAmelCase					:       Dict):
   import decorator
   from requests.exceptions import HTTPError

   def _wrapper(_UpperCAmelCase					:       Optional[Any],      *_UpperCAmelCase					:       int,      **_UpperCAmelCase					:       Optional[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 						lowercase__	:






   '''simple docstring'''







   def __init__(			self ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__   ):

      '''simple docstring'''







      UpperCamelCase       =  returncode
      UpperCamelCase       =  stdout
      UpperCamelCase       =  stderr




async def  __snake_case     (    _UpperCAmelCase					:       Tuple,      _UpperCAmelCase					:       Optional[int]):
   while True:
      UpperCamelCase       =  await stream.readline()
      if line:
         callback(_UpperCAmelCase)
      else:
         break



async def  __snake_case     (    _UpperCAmelCase					:       List[str],      _UpperCAmelCase					:       int=None,      _UpperCAmelCase					:       List[Any]=None,      _UpperCAmelCase					:       List[Any]=None,      _UpperCAmelCase					:       str=False,      _UpperCAmelCase					:       Tuple=False):
   if echo:
      print('''\nRunning: ''',      ''' '''.join(_UpperCAmelCase))

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

   UpperCamelCase       =  []
   UpperCamelCase       =  []

   def tee(_UpperCAmelCase					:       Dict,      _UpperCAmelCase					:       Optional[Any],      _UpperCAmelCase					:       Optional[int],      _UpperCAmelCase					:       Tuple=""):
      UpperCamelCase       =  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  __snake_case     (    _UpperCAmelCase					:       str,      _UpperCAmelCase					:       Union[str, Any]=None,      _UpperCAmelCase					:       Any=None,      _UpperCAmelCase					:       Any=180,      _UpperCAmelCase					:       str=False,      _UpperCAmelCase					:       List[str]=True):
   UpperCamelCase       =  asyncio.get_event_loop()
   UpperCamelCase       =  loop.run_until_complete(
       _stream_subprocess(_UpperCAmelCase,      env=_UpperCAmelCase,      stdin=_UpperCAmelCase,      timeout=_UpperCAmelCase,      quiet=_UpperCAmelCase,      echo=_UpperCAmelCase))

   UpperCamelCase       =  ''' '''.join(_UpperCAmelCase)
   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  __snake_case     (    ):
   UpperCamelCase       =  os.environ.get('''PYTEST_XDIST_WORKER''',      '''gw0''')
   UpperCamelCase       =  re.sub(R'''^gw''',      '''''',      _UpperCAmelCase,      0,      re.M)
   return int(_UpperCAmelCase)



def  __snake_case     (    ):
   UpperCamelCase       =  2_9500
   UpperCamelCase       =  pytest_xdist_worker_id()
   return port + uniq_delta







'''simple docstring'''


import os
import re
import unicodedata
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union

import sentencepiece as spm

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


if is_torch_available():
   import torch


if TYPE_CHECKING:
   from transformers.pipelines.conversational import Conversation


snake_case_ :  Union[str, Any]     =					logging.get_logger(__name__)
snake_case_ :  Union[str, Any]     =					{'vocab_file': 'spiece.model'}

snake_case_ :  Any     =					{
    'vocab_file': {
        'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model',
        'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model',
        'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model',
        'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model',
        'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model',
    }
}

snake_case_ :  Dict     =					{
    'AI-Sweden/gpt-sw3-126m': 2_048,
    'AI-Sweden/gpt-sw3-350m': 2_048,
    'AI-Sweden/gpt-sw3-1.6b': 2_048,
    'AI-Sweden/gpt-sw3-6.7b': 2_048,
    'AI-Sweden/gpt-sw3-20b': 2_048,
}


class 						lowercase__	(  snake_case_   ):






   '''simple docstring'''







   _snake_case		   =							VOCAB_FILES_NAMES
   _snake_case		   =							PRETRAINED_VOCAB_FILES_MAP
   _snake_case		   =							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   _snake_case		   =							['''input_ids''', '''attention_mask''']







   def __init__(			self ,   lowerCamelCase__ ,   lowerCamelCase__=False ,   lowerCamelCase__=False ,   lowerCamelCase__=False ,   lowerCamelCase__=None ,   lowerCamelCase__=None ,   lowerCamelCase__=None ,   lowerCamelCase__=None ,   lowerCamelCase__ = None ,   **lowerCamelCase__ ,   ):

      '''simple docstring'''







      UpperCamelCase       =  {} if sp_model_kwargs is None else sp_model_kwargs

      UpperCamelCase       =  kwargs.get('''name_or_path'''   )
      if name_or_path is None:
         logger.warning(
             '''name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,'''
             ''' you are testing the model, this can safely be ignored'''   )
         UpperCamelCase       =  '''None'''

      # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing
      UpperCamelCase       =  '''<|endoftext|>''' if eos_token is None else eos_token
      UpperCamelCase       =  '''<unk>''' if unk_token is None else unk_token
      if "gpt-sw3-7b" in name_or_path:
         UpperCamelCase       =  unk_token if pad_token is None else pad_token
         UpperCamelCase       =  eos_token if bos_token is None else bos_token
      else:
         UpperCamelCase       =  '''<pad>''' if pad_token is None else pad_token
         UpperCamelCase       =  '''<s>''' if bos_token is None else bos_token

      super().__init__(
          do_lower_case=lowerCamelCase__ ,   remove_space=lowerCamelCase__ ,   keep_accents=lowerCamelCase__ ,   bos_token=lowerCamelCase__ ,   eos_token=lowerCamelCase__ ,   unk_token=lowerCamelCase__ ,   pad_token=lowerCamelCase__ ,   sp_model_kwargs=self.sp_model_kwargs ,   **lowerCamelCase__ ,   )

      UpperCamelCase       =  do_lower_case
      UpperCamelCase       =  remove_space
      UpperCamelCase       =  keep_accents
      UpperCamelCase       =  vocab_file

      UpperCamelCase       =  spm.SentencePieceProcessor(**self.sp_model_kwargs   )
      self.sp_model.Load(lowerCamelCase__   )

      # Used for whitespace normalization in input texts
      # fmt : off
      UpperCamelCase       =  {''' ''', ''' ''', ''' ''', ''' ''', ''' ''', '''　''', ''' ''', ''' ''', ''' ''', ''' ''', '''￼''', ''''''}
      # fmt : on

      # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing
      UpperCamelCase       =  re.compile(
          f'[{"".join(map(lowerCamelCase__ ,   list(range(0 ,   9   )   ) + list(range(1_1 ,   3_2   )   ) + list(range(1_2_7 ,   1_6_0   )   ) + [1_6_0, 1_7_3, 8_2_0_3]   )   )}]'   )







   def __getstate__(			self   ):

      '''simple docstring'''







      UpperCamelCase       =  self.__dict__.copy()
      UpperCamelCase       =  None
      return state







   def __setstate__(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      UpperCamelCase       =  d

      # for backward compatibility
      if not hasattr(self ,   '''sp_model_kwargs'''   ):
         UpperCamelCase       =  {}

      UpperCamelCase       =  spm.SentencePieceProcessor(**self.sp_model_kwargs   )
      self.sp_model.Load(self.vocab_file   )







   @property
   # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size
   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      return len(self.sp_model   )







   def       UpperCAmelCase				(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      UpperCamelCase       =  self.non_printing_characters_re.sub('''''' ,   lowerCamelCase__   )

      # Normalize whitespaces
      UpperCamelCase       =  ''''''.join([char if char not in self.whitespaces else ''' ''' for char in text]   )

      # NFC Unicode normalization
      UpperCamelCase       =  unicodedata.normalize('''NFC''' ,   lowerCamelCase__   )
      return text







   def       UpperCAmelCase				(			self ,   lowerCamelCase__ ,   **lowerCamelCase__   ):

      '''simple docstring'''







      UpperCamelCase       =  self.preprocess_text(lowerCamelCase__   )
      return self.sp_model.encode(lowerCamelCase__ ,   out_type=lowerCamelCase__   )







   def       UpperCAmelCase				(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      return self.sp_model.PieceToId(lowerCamelCase__   )







   def       UpperCAmelCase				(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      return self.sp_model.IdToPiece(lowerCamelCase__   )







   @staticmethod
   def       UpperCAmelCase				(			lowerCamelCase__   ):

      '''simple docstring'''







      return out_string







   def       UpperCAmelCase				(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      UpperCamelCase       =  []
      UpperCamelCase       =  ''''''
      UpperCamelCase       =  False
      for token in tokens:
         # make sure that special tokens are not decoded using sentencepiece model
         if token in self.all_special_tokens:
            # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document
            if not prev_is_special:
               out_string += " "

            out_string += self.sp_model.decode(lowerCamelCase__   ) + token
            UpperCamelCase       =  True
            UpperCamelCase       =  []
         else:
            current_sub_tokens.append(lowerCamelCase__   )
            UpperCamelCase       =  False
      out_string += self.sp_model.decode(lowerCamelCase__   )

      return out_string







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      UpperCamelCase       =  {self.convert_ids_to_tokens(lowerCamelCase__   ): i for i in range(self.vocab_size   )}
      vocab.update(self.added_tokens_encoder   )
      return vocab







   def       UpperCAmelCase				(			self ,   lowerCamelCase__ ,   lowerCamelCase__ = None   ):

      '''simple docstring'''







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

      if os.path.abspath(self.vocab_file   ) != os.path.abspath(lowerCamelCase__   ) and os.path.isfile(self.vocab_file   ):
         copyfile(self.vocab_file ,   lowerCamelCase__   )
      elif not os.path.isfile(self.vocab_file   ):
         with open(lowerCamelCase__ ,   '''wb'''   ) as fi:
            UpperCamelCase       =  self.sp_model.serialized_model_proto()
            fi.write(lowerCamelCase__   )

      return (out_vocab_file,)







   def       UpperCAmelCase				(			self ,   lowerCamelCase__ ,   lowerCamelCase__ = False   ):

      '''simple docstring'''







      if isinstance(lowerCamelCase__ ,   lowerCamelCase__   ):
         UpperCamelCase       =  self.preprocess_text(lowerCamelCase__   )
         UpperCamelCase       =  self.sp_model.encode(lowerCamelCase__   )
      else:
         UpperCamelCase       =  [self.preprocess_text(lowerCamelCase__   ) for t in text]
         UpperCamelCase       =  self.sp_model.encode(lowerCamelCase__   )

      if return_tensors is True or return_tensors == "pt":
         UpperCamelCase       =  torch.tensor(lowerCamelCase__   )

      return token_ids







   def       UpperCAmelCase				(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      return self.sp_model.decode(lowerCamelCase__   )







   def       UpperCAmelCase				(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      UpperCamelCase       =  [f'User: {text}' if is_user else f'Bot: {text}' for is_user, text in conversation.iter_texts()]
      UpperCamelCase       =  (
          f'{self.eos_token}{self.bos_token}' + f'{self.bos_token}'.join(lowerCamelCase__   ) + f'{self.bos_token}Bot:'
      )
      return self.encode(text=lowerCamelCase__   )





