



"""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

lowercase__						:							Tuple        =      logging.get_logger(__name__)

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

lowercase__						:							List[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""",
    },
}

lowercase__						:							int        =      {
    """gpt2""": 1_0_2_4,
    """gpt2-medium""": 1_0_2_4,
    """gpt2-large""": 1_0_2_4,
    """gpt2-xl""": 1_0_2_4,
    """distilgpt2""": 1_0_2_4,
}

@lru_cache()
def 							UpperCamelCase_       (       )		->  Dict:

  """simple docstring"""




  lowerCAmelCase_  :							List[str]								=					(
      list(range(ord('!'		)       ,  ord('~'		) + 1		)		) + list(range(ord('¡'		)       ,  ord('¬'		) + 1		)		) + list(range(ord('®'		)       ,  ord('ÿ'		) + 1		)		)
  )
  lowerCAmelCase_  :							Dict								=					bs[:]
  lowerCAmelCase_  :							List[Any]								=					0
  for b in range(2**8		):
    if b not in bs:
      bs.append(lowerCAmelCase__		)
      cs.append(2**8 + n		)
      n += 1
  lowerCAmelCase_  :							Any								=					[chr(lowerCAmelCase__		) for n in cs]
  return dict(zip(lowerCAmelCase__       ,  lowerCAmelCase__		)		)

def 							UpperCamelCase_       (       lowerCAmelCase__ :							Optional[int]		)		->  Optional[int]:

  """simple docstring"""




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







class  UpperCamelCase__  (      lowercase_    ):




      """simple docstring"""




      _SCREAMING_SNAKE_CASE    							=	VOCAB_FILES_NAMES
      _SCREAMING_SNAKE_CASE    							=	PRETRAINED_VOCAB_FILES_MAP
      _SCREAMING_SNAKE_CASE    							=	PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      _SCREAMING_SNAKE_CASE    							=	["""input_ids""", """attention_mask"""]



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

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

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



      @property
      def 	SCREAMING_SNAKE_CASE__					( self							: Union[str, Any]			):
        return len(self.encoder			)



      def 	SCREAMING_SNAKE_CASE__					( self							: List[str]			):
        return dict(self.encoder       ,     **self.added_tokens_encoder			)



      def 	SCREAMING_SNAKE_CASE__					( self							: str       ,     SCREAMING_SNAKE_CASE_							: List[str]			):
        if token in self.cache:
          return self.cache[token]
        lowerCAmelCase_  :							List[str]								=					tuple(SCREAMING_SNAKE_CASE_			)
        lowerCAmelCase_  :							str								=					get_pairs(SCREAMING_SNAKE_CASE_			)

        if not pairs:
          return token

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

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



      def 	SCREAMING_SNAKE_CASE__					( self							: List[str]       ,     SCREAMING_SNAKE_CASE_							: Optional[int]       ,     SCREAMING_SNAKE_CASE_							: int=None			):
        if self.add_bos_token:
          lowerCAmelCase_  :							Union[str, Any]								=					[self.bos_token_id]
        else:
          lowerCAmelCase_  :							Optional[int]								=					[]

        lowerCAmelCase_  :							List[Any]								=					bos_token_ids + token_ids_a

        if token_ids_a is None:
          return output

        return output + bos_token_ids + token_ids_a



      def 	SCREAMING_SNAKE_CASE__					( self							: Tuple       ,     SCREAMING_SNAKE_CASE_							: List[int]       ,     SCREAMING_SNAKE_CASE_							: Optional[List[int]] = None       ,     SCREAMING_SNAKE_CASE_							: bool = False			):
        if already_has_special_tokens:
          return super().get_special_tokens_mask(
              token_ids_a=SCREAMING_SNAKE_CASE_       ,     token_ids_a=SCREAMING_SNAKE_CASE_       ,     already_has_special_tokens=SCREAMING_SNAKE_CASE_			)

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

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



      def 	SCREAMING_SNAKE_CASE__					( self							: str       ,     SCREAMING_SNAKE_CASE_							: int			):
        lowerCAmelCase_  :							List[Any]								=					[]
        for token in re.findall(self.pat       ,     SCREAMING_SNAKE_CASE_			):
          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(SCREAMING_SNAKE_CASE_			).split(' '			)			)
        return bpe_tokens



      def 	SCREAMING_SNAKE_CASE__					( self							: Optional[int]       ,     SCREAMING_SNAKE_CASE_							: Any			):
        return self.encoder.get(SCREAMING_SNAKE_CASE_       ,     self.encoder.get(self.unk_token			)			)



      def 	SCREAMING_SNAKE_CASE__					( self							: Union[str, Any]       ,     SCREAMING_SNAKE_CASE_							: Dict			):
        return self.decoder.get(SCREAMING_SNAKE_CASE_			)



      def 	SCREAMING_SNAKE_CASE__					( self							: List[Any]       ,     SCREAMING_SNAKE_CASE_							: Tuple			):
        lowerCAmelCase_  :							Optional[Any]								=					''.join(SCREAMING_SNAKE_CASE_			)
        lowerCAmelCase_  :							Optional[Any]								=					bytearray([self.byte_decoder[c] for c in text]			).decode('utf-8'       ,     errors=self.errors			)
        return text



      def 	SCREAMING_SNAKE_CASE__					( self							: List[Any]       ,     SCREAMING_SNAKE_CASE_							: str       ,     SCREAMING_SNAKE_CASE_							: Optional[str] = None			):
        if not os.path.isdir(SCREAMING_SNAKE_CASE_			):
          logger.error(F"Vocabulary path ({save_directory}) should be a directory"			)
          return
        lowerCAmelCase_  :							Dict								=					os.path.join(
            SCREAMING_SNAKE_CASE_       ,     (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']			)
        lowerCAmelCase_  :							Optional[Any]								=					os.path.join(
            SCREAMING_SNAKE_CASE_       ,     (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file']			)

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

        lowerCAmelCase_  :							str								=					0
        with open(SCREAMING_SNAKE_CASE_       ,     '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 SCREAMING_SNAKE_CASE_			: 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_  :							Optional[int]								=					token_index
            writer.write(' '.join(SCREAMING_SNAKE_CASE_			) + '\n'			)
            index += 1

        return vocab_file, merge_file



      def 	SCREAMING_SNAKE_CASE__					( self							: List[Any]       ,     SCREAMING_SNAKE_CASE_							: str       ,     SCREAMING_SNAKE_CASE_							: int=False       ,     **SCREAMING_SNAKE_CASE_							: Any			):
        lowerCAmelCase_  :							Tuple								=					kwargs.pop('add_prefix_space'       ,     self.add_prefix_space			)
        if is_split_into_words or add_prefix_space:
          lowerCAmelCase_  :							Tuple								=					' ' + text
        return (text, kwargs)





      def 	SCREAMING_SNAKE_CASE__					( self							: Dict       ,     SCREAMING_SNAKE_CASE_							: "Conversation"			):
        lowerCAmelCase_  :							Any								=					[]
        for is_user, text in conversation.iter_texts():
          input_ids.extend(self.encode(SCREAMING_SNAKE_CASE_       ,     add_special_tokens=SCREAMING_SNAKE_CASE_			) + [self.eos_token_id]			)
        if len(SCREAMING_SNAKE_CASE_			) > self.model_max_length:
          lowerCAmelCase_  :							List[Any]								=					input_ids[-self.model_max_length :]
        return input_ids










"""simple docstring"""







from .stack import Stack

def 							UpperCamelCase_       (       lowerCAmelCase__ :							str		)		->  bool:

  """simple docstring"""




  lowerCAmelCase_  :							Stack[str]								=					Stack()
  lowerCAmelCase_  :							List[str]								=					{'(': ')', '[': ']', '{': '}'}
  for bracket in parentheses:
    if bracket in bracket_pairs:
      stack.push(lowerCAmelCase__		)
    elif bracket in (")", "]", "}"):
      if stack.is_empty() or bracket_pairs[stack.pop()] != bracket:
        return False
  return stack.is_empty()


if __name__ == "__main__":
     from doctest import testmod

     testmod()

     lowercase__						:							List[str]        =      ["""((()))""", """((())""", """(()))"""]
     print("""Balanced parentheses demonstration:\n""")
     for example in examples:
          lowercase__						:							List[Any]        =      """""" if balanced_parentheses(example) else """not """
          print(f'{example} is {not_str}balanced')





