


"""simple docstring"""






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

import regex as re

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


if TYPE_CHECKING:
  from transformers.pipelines.conversational import Conversation

_lowerCAmelCase				:  Dict 					=     logging.get_logger(__name__)

_lowerCAmelCase				:  Optional[int] 					=     {
    '''vocab_file''': '''vocab.json''',
    '''merges_file''': '''merges.txt''',
}

_lowerCAmelCase				:  str 					=     {
    '''vocab_file''': {
        '''gpt2''': '''https://huggingface.co/gpt2/resolve/main/vocab.json''',
        '''gpt2-medium''': '''https://huggingface.co/gpt2-medium/resolve/main/vocab.json''',
        '''gpt2-large''': '''https://huggingface.co/gpt2-large/resolve/main/vocab.json''',
        '''gpt2-xl''': '''https://huggingface.co/gpt2-xl/resolve/main/vocab.json''',
        '''distilgpt2''': '''https://huggingface.co/distilgpt2/resolve/main/vocab.json''',
    },
    '''merges_file''': {
        '''gpt2''': '''https://huggingface.co/gpt2/resolve/main/merges.txt''',
        '''gpt2-medium''': '''https://huggingface.co/gpt2-medium/resolve/main/merges.txt''',
        '''gpt2-large''': '''https://huggingface.co/gpt2-large/resolve/main/merges.txt''',
        '''gpt2-xl''': '''https://huggingface.co/gpt2-xl/resolve/main/merges.txt''',
        '''distilgpt2''': '''https://huggingface.co/distilgpt2/resolve/main/merges.txt''',
    },
}

_lowerCAmelCase				:  int 					=     {
    '''gpt2''': 1024,
    '''gpt2-medium''': 1024,
    '''gpt2-large''': 1024,
    '''gpt2-xl''': 1024,
    '''distilgpt2''': 1024,
}







@lru_cache()
def     lowerCamelCase_(						)  ->			str:
   '''simple docstring'''





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







def     lowerCamelCase_(						_lowerCamelCase    )  ->			Dict:
   '''simple docstring'''





   _lowerCamelCase					:							Tuple				=			set()
   _lowerCamelCase					:							Optional[int]				=			word[0]
   for char in word[1:]:
      pairs.add((prev_char, char)    )
      _lowerCamelCase					:							str				=			char
   return pairs




class 				A_	(    a_      ):
  lowerCAmelCase__	       =     VOCAB_FILES_NAMES
  lowerCAmelCase__	       =     PRETRAINED_VOCAB_FILES_MAP
  lowerCAmelCase__	       =     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  lowerCAmelCase__	       =     ['input_ids', 'attention_mask']


  def __init__(       self:		str				,__lowerCAmelCase:		Optional[Any]				,__lowerCAmelCase:		Optional[int]				,__lowerCAmelCase:		Tuple="replace"				,__lowerCAmelCase:		int="<|endoftext|>"				,__lowerCAmelCase:		Union[str, Any]="<|endoftext|>"				,__lowerCAmelCase:		str="<|endoftext|>"				,__lowerCAmelCase:		str=None				,__lowerCAmelCase:		Any=False				,__lowerCAmelCase:		Optional[int]=False				,**__lowerCAmelCase:		Any				,):







     '''simple docstring'''







     _lowerCamelCase					:							List[str]				=			AddedToken(__lowerCAmelCase				,lstrip=__lowerCAmelCase				,rstrip=__lowerCAmelCase  ) if isinstance(__lowerCAmelCase				,__lowerCAmelCase  ) else bos_token
     _lowerCamelCase					:							int				=			AddedToken(__lowerCAmelCase				,lstrip=__lowerCAmelCase				,rstrip=__lowerCAmelCase  ) if isinstance(__lowerCAmelCase				,__lowerCAmelCase  ) else eos_token
     _lowerCamelCase					:							Optional[int]				=			AddedToken(__lowerCAmelCase				,lstrip=__lowerCAmelCase				,rstrip=__lowerCAmelCase  ) if isinstance(__lowerCAmelCase				,__lowerCAmelCase  ) else unk_token
     _lowerCamelCase					:							Any				=			AddedToken(__lowerCAmelCase				,lstrip=__lowerCAmelCase				,rstrip=__lowerCAmelCase  ) if isinstance(__lowerCAmelCase				,__lowerCAmelCase  ) else pad_token
     super().__init__(
         errors=__lowerCAmelCase				,unk_token=__lowerCAmelCase				,bos_token=__lowerCAmelCase				,eos_token=__lowerCAmelCase				,pad_token=__lowerCAmelCase				,add_prefix_space=__lowerCAmelCase				,add_bos_token=__lowerCAmelCase				,**__lowerCAmelCase				,)
     _lowerCamelCase					:							int				=			add_bos_token

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

     # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
     _lowerCamelCase					:							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 				_lowercase (       self:		Union[str, Any]  ):







     '''simple docstring'''







     return len(self.encoder  )


  def 				_lowercase (       self:		Dict  ):







     '''simple docstring'''







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


  def 				_lowercase (       self:		Any				,__lowerCAmelCase:		List[Any]  ):







     '''simple docstring'''







     if token in self.cache:
        return self.cache[token]
     _lowerCamelCase					:							List[str]				=			tuple(__lowerCAmelCase  )
     _lowerCamelCase					:							str				=			get_pairs(__lowerCAmelCase  )

     if not pairs:
        return token

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

           if word[i] == first and i < len(__lowerCAmelCase  ) - 1 and word[i + 1] == second:
              new_word.append(first + second  )
              i += 2
           else:
              new_word.append(word[i]  )
              i += 1
        _lowerCamelCase					:							str				=			tuple(__lowerCAmelCase  )
        _lowerCamelCase					:							Union[str, Any]				=			new_word
        if len(__lowerCAmelCase  ) == 1:
           break
        else:
           _lowerCamelCase					:							str				=			get_pairs(__lowerCAmelCase  )
     _lowerCamelCase					:							Dict				=			' '.join(__lowerCAmelCase  )
     _lowerCamelCase					:							List[Any]				=			word
     return word


  def 				_lowercase (       self:		List[str]				,__lowerCAmelCase:		Tuple				,__lowerCAmelCase:		int=None  ):







     '''simple docstring'''







     if self.add_bos_token:
        _lowerCamelCase					:							List[Any]				=			[self.bos_token_id]
     else:
        _lowerCamelCase					:							List[str]				=			[]

     _lowerCamelCase					:							Dict				=			bos_token_ids + token_ids_a

     if token_ids_a is None:
        return output

     return output + bos_token_ids + token_ids_a


  def 				_lowercase (       self:		Optional[Any]				,__lowerCAmelCase:		List[int]				,__lowerCAmelCase:		Optional[List[int]] = None				,__lowerCAmelCase:		bool = False  ):







     '''simple docstring'''







     if already_has_special_tokens:
        return super().get_special_tokens_mask(
            token_ids_a=__lowerCAmelCase				,token_ids_a=__lowerCAmelCase				,already_has_special_tokens=__lowerCAmelCase  )

     if not self.add_bos_token:
        return super().get_special_tokens_mask(
            token_ids_a=__lowerCAmelCase				,token_ids_a=__lowerCAmelCase				,already_has_special_tokens=__lowerCAmelCase  )

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


  def 				_lowercase (       self:		Union[str, Any]				,__lowerCAmelCase:		int  ):







     '''simple docstring'''







     _lowerCamelCase					:							str				=			[]
     for token in re.findall(self.pat				,__lowerCAmelCase  ):
        _lowerCamelCase					:							Dict				=			''.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(__lowerCAmelCase  ).split(" "  )  )
     return bpe_tokens


  def 				_lowercase (       self:		Any				,__lowerCAmelCase:		List[str]  ):







     '''simple docstring'''







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


  def 				_lowercase (       self:		List[str]				,__lowerCAmelCase:		Optional[int]  ):







     '''simple docstring'''







     return self.decoder.get(__lowerCAmelCase  )


  def 				_lowercase (       self:		Optional[int]				,__lowerCAmelCase:		Union[str, Any]  ):







     '''simple docstring'''







     _lowerCamelCase					:							Any				=			''.join(__lowerCAmelCase  )
     _lowerCamelCase					:							Dict				=			bytearray([self.byte_decoder[c] for c in text]  ).decode("utf-8"				,errors=self.errors  )
     return text


  def 				_lowercase (       self:		Tuple				,__lowerCAmelCase:		str				,__lowerCAmelCase:		Optional[str] = None  ):







     '''simple docstring'''







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

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

     _lowerCamelCase					:							Any				=			0
     with open(__lowerCAmelCase				,"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 __lowerCAmelCase  : 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					:							Dict				=			token_index
           writer.write(" ".join(__lowerCAmelCase  ) + "\n"  )
           index += 1

     return vocab_file, merge_file


  def 				_lowercase (       self:		Tuple				,__lowerCAmelCase:		List[str]				,__lowerCAmelCase:		List[str]=False				,**__lowerCAmelCase:		List[Any]  ):







     '''simple docstring'''







     _lowerCamelCase					:							Any				=			kwargs.pop("add_prefix_space"				,self.add_prefix_space  )
     if is_split_into_words or add_prefix_space:
        _lowerCamelCase					:							Dict				=			' ' + text
     return (text, kwargs)






  def 				_lowercase (       self:		List[Any]				,__lowerCAmelCase:		"Conversation"  ):







     '''simple docstring'''







     _lowerCamelCase					:							Optional[int]				=			[]
     for is_user, text in conversation.iter_texts():
        input_ids.extend(self.encode(__lowerCAmelCase				,add_special_tokens=__lowerCAmelCase  ) + [self.eos_token_id]  )
     if len(__lowerCAmelCase  ) > self.model_max_length:
        _lowerCamelCase					:							Optional[int]				=			input_ids[-self.model_max_length :]
     return input_ids
import json
import os
from functools import lru_cache
from typing import TYPE_CHECKING, List, Optional, Tuple, Union

import numpy as np
import regex as re

from ...utils import is_tf_available, is_torch_available, logging


if TYPE_CHECKING:
 if is_torch_available():
  import torch
 if is_tf_available():
  import tensorflow as tf

from ...tokenization_utils import AddedToken, PreTrainedTokenizer


UpperCAmelCase							= logging.get_logger(__name__)

UpperCAmelCase							= {
    '''vocab_file''': '''vocab.json''',
    '''merges_file''': '''merges.txt''',
}

UpperCAmelCase							= {
    '''vocab_file''': {
        '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json''',
    },
    '''merges_file''': {
        '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt''',
    },
}

UpperCAmelCase							= {
    '''Salesforce/codegen-350M-mono''': 20_48,
}


@lru_cache()
def SCREAMING_SNAKE_CASE (   ):
       _UpperCamelCase   :				Any       =     (
           list(range(ord('!' )						,  ord('~' ) + 1 ) ) + list(range(ord('¡' )						,  ord('¬' ) + 1 ) ) + list(range(ord('®' )						,  ord('ÿ' ) + 1 ) )
       )
       _UpperCamelCase   :				int       =     bs[:]
       _UpperCamelCase   :				Any       =     0
       for b in range(2**8 ):
              if b not in bs:
                     bs.append(lowercase_ )
                     cs.append(2**8 + n )
                     n += 1
       _UpperCamelCase   :				str       =     [chr(lowercase_ ) for n in cs]
       return dict(zip(lowercase_						,  lowercase_ ) )


def SCREAMING_SNAKE_CASE (   lowercase_:		int ):
       _UpperCamelCase   :				List[str]       =     set()
       _UpperCamelCase   :				Optional[int]       =     word[0]
       for char in word[1:]:
              pairs.add((prev_char, char) )
              _UpperCamelCase   :				Optional[Any]       =     char
       return pairs





class       __lowerCAmelCase     (				a_  ):



 '''simple docstring'''
 _lowerCamelCase  :		Union[str, Any] 			=       VOCAB_FILES_NAMES
 _lowerCamelCase  :		Optional[int] 			=       PRETRAINED_VOCAB_FILES_MAP
 _lowerCamelCase  :		List[str] 			=       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 _lowerCamelCase  :		Optional[int] 			=       ['input_ids', 'attention_mask']

 def __init__(	self				:						Union[str, Any]				,	lowerCamelCase				:						Tuple				,	lowerCamelCase				:						str				,	lowerCamelCase				:						Optional[Any]="replace"				,	lowerCamelCase				:						int="<|endoftext|>"				,	lowerCamelCase				:						Dict="<|endoftext|>"				,	lowerCamelCase				:						Dict="<|endoftext|>"				,	lowerCamelCase				:						str=None				,	lowerCamelCase				:						List[Any]=False				,	lowerCamelCase				:						Optional[int]=False				,	**lowerCamelCase				:						Optional[Any]				,	)       ->							int:
        _UpperCamelCase   :				int       =     AddedToken(lowerCamelCase				,	lstrip=lowerCamelCase				,	rstrip=lowerCamelCase     ) if isinstance(lowerCamelCase				,	lowerCamelCase     ) else bos_token
        _UpperCamelCase   :				Any       =     AddedToken(lowerCamelCase				,	lstrip=lowerCamelCase				,	rstrip=lowerCamelCase     ) if isinstance(lowerCamelCase				,	lowerCamelCase     ) else eos_token
        _UpperCamelCase   :				Dict       =     AddedToken(lowerCamelCase				,	lstrip=lowerCamelCase				,	rstrip=lowerCamelCase     ) if isinstance(lowerCamelCase				,	lowerCamelCase     ) else unk_token
        _UpperCamelCase   :				Dict       =     AddedToken(lowerCamelCase				,	lstrip=lowerCamelCase				,	rstrip=lowerCamelCase     ) if isinstance(lowerCamelCase				,	lowerCamelCase     ) else pad_token
        super().__init__(
            errors=lowerCamelCase				,	unk_token=lowerCamelCase				,	bos_token=lowerCamelCase				,	eos_token=lowerCamelCase				,	pad_token=lowerCamelCase				,	add_prefix_space=lowerCamelCase				,	add_bos_token=lowerCamelCase				,	**lowerCamelCase				,	)
        _UpperCamelCase   :				List[str]       =     add_bos_token

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

        # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
        _UpperCamelCase   :				Union[str, Any]       =     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				:						Optional[Any]     )       ->							Union[str, Any]:
        return len(self.encoder     )

 def     __snake_case    (	self				:						Union[str, Any]     )       ->							Optional[Any]:
        return dict(self.encoder				,	**self.added_tokens_encoder     )

 def     __snake_case    (	self				:						int				,	lowerCamelCase				:						Dict     )       ->							Union[str, Any]:
        if token in self.cache:
               return self.cache[token]
        _UpperCamelCase   :				Dict       =     tuple(lowerCamelCase     )
        _UpperCamelCase   :				Union[str, Any]       =     get_pairs(lowerCamelCase     )

        if not pairs:
               return token

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

                      if word[i] == first and i < len(lowerCamelCase     ) - 1 and word[i + 1] == second:
                             new_word.append(first + second     )
                             i += 2
                      else:
                             new_word.append(word[i]     )
                             i += 1
               _UpperCamelCase   :				List[str]       =     tuple(lowerCamelCase     )
               _UpperCamelCase   :				Tuple       =     new_word
               if len(lowerCamelCase     ) == 1:
                      break
               else:
                      _UpperCamelCase   :				int       =     get_pairs(lowerCamelCase     )
        _UpperCamelCase   :				List[Any]       =     ' '.join(lowerCamelCase     )
        _UpperCamelCase   :				List[str]       =     word
        return word

 def     __snake_case    (	self				:						Optional[Any]				,	lowerCamelCase				:						str				,	lowerCamelCase				:						Any=None     )       ->							Any:
        if self.add_bos_token:
               _UpperCamelCase   :				List[str]       =     [self.bos_token_id]
        else:
               _UpperCamelCase   :				List[str]       =     []

        _UpperCamelCase   :				Union[str, Any]       =     bos_token_ids + token_ids_a

        if token_ids_a is None:
               return output

        return output + bos_token_ids + token_ids_a

 def     __snake_case    (	self				:						Union[str, Any]				,	lowerCamelCase				:						Union[str, Any]     )       ->							str:
        _UpperCamelCase   :				Tuple       =     []
        for token in re.findall(self.pat				,	lowerCamelCase     ):
               _UpperCamelCase   :				int       =     ''.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(lowerCamelCase     ).split(' '     )     )
        return bpe_tokens

 def     __snake_case    (	self				:						int				,	lowerCamelCase				:						Any     )       ->							List[str]:
        return self.encoder.get(lowerCamelCase				,	self.encoder.get(self.unk_token     )     )

 def     __snake_case    (	self				:						Optional[int]				,	lowerCamelCase				:						List[Any]     )       ->							List[str]:
        return self.decoder.get(lowerCamelCase     )

 def     __snake_case    (	self				:						Optional[int]				,	lowerCamelCase				:						Optional[Any]     )       ->							List[Any]:
        _UpperCamelCase   :				Union[str, Any]       =     ''.join(lowerCamelCase     )
        _UpperCamelCase   :				Tuple       =     bytearray([self.byte_decoder[c] for c in text]     ).decode('utf-8'				,	errors=self.errors     )
        return text

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

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

        _UpperCamelCase   :				Any       =     0
        with open(lowerCamelCase				,	'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 lowerCamelCase     : 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   :				Dict       =     token_index
                      writer.write(' '.join(lowerCamelCase     ) + '\n'     )
                      index += 1

        return vocab_file, merge_file

 def     __snake_case    (	self				:						Any				,	lowerCamelCase				:						Optional[int]				,	lowerCamelCase				:						int=False				,	**lowerCamelCase				:						Any     )       ->							Tuple:
        _UpperCamelCase   :				Optional[int]       =     kwargs.pop('add_prefix_space'				,	self.add_prefix_space     )
        if is_split_into_words or add_prefix_space:
               _UpperCamelCase   :				Union[str, Any]       =     ' ' + text
        return (text, kwargs)

 def     __snake_case    (	self				:						str				,	lowerCamelCase				:						Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"]				,	lowerCamelCase				:						bool = False				,	lowerCamelCase				:						bool = None				,	lowerCamelCase				:						Optional[List[str]] = None				,	**lowerCamelCase				:						Union[str, Any]				,	)       ->							str:
        _UpperCamelCase   :				List[str]       =     super()._decode(
            token_ids=lowerCamelCase				,	skip_special_tokens=lowerCamelCase				,	clean_up_tokenization_spaces=lowerCamelCase				,	**lowerCamelCase				,	)

        if truncate_before_pattern is not None and len(lowerCamelCase     ) > 0:
               _UpperCamelCase   :				Union[str, Any]       =     self.truncate(lowerCamelCase				,	lowerCamelCase     )

        return decoded_text

 def     __snake_case    (	self				:						Any				,	lowerCamelCase				:						Dict				,	lowerCamelCase				:						Optional[int]     )       ->							Any:
        def find_re(lowerCamelCase				:						int				,	lowerCamelCase				:						int				,	lowerCamelCase				:						List[Any]     ):
               _UpperCamelCase   :				Dict       =     pattern.search(lowerCamelCase				,	lowerCamelCase     )
               return m.start() if m else -1

        _UpperCamelCase   :				int       =     [re.compile(lowerCamelCase				,	re.MULTILINE     ) for pattern in truncate_before_pattern]

        _UpperCamelCase   :				Union[str, Any]       =     list(re.finditer('^print'				,	lowerCamelCase				,	re.MULTILINE     )     )

        if len(lowerCamelCase     ) > 1:
               _UpperCamelCase   :				List[Any]       =     completion[: prints[1].start()]

        _UpperCamelCase   :				Dict       =     list(re.finditer('^def'				,	lowerCamelCase				,	re.MULTILINE     )     )

        if len(lowerCamelCase     ) > 1:
               _UpperCamelCase   :				Tuple       =     completion[: defs[1].start()]

        _UpperCamelCase   :				Optional[Any]       =     0

        _UpperCamelCase   :				int       =     [
            pos for pos in [find_re(lowerCamelCase				,	lowerCamelCase				,	lowerCamelCase     ) for terminal in terminals] if pos != -1
        ]

        if len(lowerCamelCase     ) > 0:
               return completion[: min(lowerCamelCase     )]
        else:
               return completion



