
'''simple docstring'''





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": 2_048,
}

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

def   A			(							A_				:       Union[str, Any]							):
						snake_case							:  Tuple			=     set()
						snake_case							:  Tuple			=     word[0]
						for char in word[1:]:
												pairs.add((prev_char, char)							)
												snake_case							:  Optional[Any]			=     char
						return pairs





class     a (					__magic_name__     ):
				_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						:					Union[str, Any],     SCREAMING_SNAKE_CASE_						:					str,     SCREAMING_SNAKE_CASE_						:					Optional[int],     SCREAMING_SNAKE_CASE_						:					Optional[Any]="replace",     SCREAMING_SNAKE_CASE_						:					List[str]="<|endoftext|>",     SCREAMING_SNAKE_CASE_						:					List[str]="<|endoftext|>",     SCREAMING_SNAKE_CASE_						:					List[str]="<|endoftext|>",     SCREAMING_SNAKE_CASE_						:					List[str]=None,     SCREAMING_SNAKE_CASE_						:					Optional[Any]=False,     SCREAMING_SNAKE_CASE_						:					Optional[Any]=False,     **SCREAMING_SNAKE_CASE_						:					Optional[int],     ):
										snake_case							:  Union[str, Any]			=     AddedToken(SCREAMING_SNAKE_CASE_,     lstrip=SCREAMING_SNAKE_CASE_,     rstrip=SCREAMING_SNAKE_CASE_   ) if isinstance(SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_   ) else bos_token
										snake_case							:  str			=     AddedToken(SCREAMING_SNAKE_CASE_,     lstrip=SCREAMING_SNAKE_CASE_,     rstrip=SCREAMING_SNAKE_CASE_   ) if isinstance(SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_   ) else eos_token
										snake_case							:  List[Any]			=     AddedToken(SCREAMING_SNAKE_CASE_,     lstrip=SCREAMING_SNAKE_CASE_,     rstrip=SCREAMING_SNAKE_CASE_   ) if isinstance(SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_   ) else unk_token
										snake_case							:  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_,     )
										snake_case							:  Optional[Any]			=     add_bos_token

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

										# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
										snake_case							:  List[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						:					str   ):
										return len(self.encoder   )




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




				def 						__snake_case				(				self						:					List[Any],     SCREAMING_SNAKE_CASE_						:					List[str]   ):
										if token in self.cache:
																return self.cache[token]
										snake_case							:  Tuple			=     tuple(SCREAMING_SNAKE_CASE_   )
										snake_case							:  Optional[Any]			=     get_pairs(SCREAMING_SNAKE_CASE_   )

										if not pairs:
																return token

										while True:
																snake_case							:  Dict			=     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
																snake_case,       snake_case							:  Tuple			=     bigram
																snake_case							:  Union[str, Any]			=     []
																snake_case							:  int			=     0
																while i < len(SCREAMING_SNAKE_CASE_   ):
																						try:
																												snake_case							:  str			=     word.index(SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_   )
																						except ValueError:
																												new_word.extend(word[i:]   )
																												break
																						else:
																												new_word.extend(word[i:j]   )
																												snake_case							:  Optional[Any]			=     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
																snake_case							:  Dict			=     tuple(SCREAMING_SNAKE_CASE_   )
																snake_case							:  int			=     new_word
																if len(SCREAMING_SNAKE_CASE_   ) == 1:
																						break
																else:
																						snake_case							:  Union[str, Any]			=     get_pairs(SCREAMING_SNAKE_CASE_   )
										snake_case							:  Optional[Any]			=     ''' '''.join(SCREAMING_SNAKE_CASE_   )
										snake_case							:  int			=     word
										return word




				def 						__snake_case				(				self						:					int,     SCREAMING_SNAKE_CASE_						:					int,     SCREAMING_SNAKE_CASE_						:					Any=None   ):
										if self.add_bos_token:
																snake_case							:  Optional[int]			=     [self.bos_token_id]
										else:
																snake_case							:  List[Any]			=     []

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




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




				def 						__snake_case				(				self						:					Union[str, Any],     SCREAMING_SNAKE_CASE_						:					Optional[int]   ):
										return self.decoder.get(SCREAMING_SNAKE_CASE_   )




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




				def 						__snake_case				(				self						:					Union[str, 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
										snake_case							:  Tuple			=     os.path.join(
										    SCREAMING_SNAKE_CASE_,     (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']   )
										snake_case							:  str			=     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'''   )

										snake_case							:  Optional[Any]			=     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!'''   )
																												snake_case							:  Optional[Any]			=     token_index
																						writer.write(''' '''.join(SCREAMING_SNAKE_CASE_   ) + '''\n'''   )
																						index += 1

										return vocab_file, merge_file




				def 						__snake_case				(				self						:					Dict,     SCREAMING_SNAKE_CASE_						:					Union[str, Any],     SCREAMING_SNAKE_CASE_						:					str=False,     **SCREAMING_SNAKE_CASE_						:					List[Any]   ):
										snake_case							:  Tuple			=     kwargs.pop('''add_prefix_space''',     self.add_prefix_space   )
										if is_split_into_words or add_prefix_space:
																snake_case							:  Dict			=     ''' ''' + text
										return (text, kwargs)




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

										if truncate_before_pattern is not None and len(SCREAMING_SNAKE_CASE_   ) > 0:
																snake_case							:  List[str]			=     self.truncate(SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_   )

										return decoded_text




				def 						__snake_case				(				self						:					Optional[Any],     SCREAMING_SNAKE_CASE_						:					Dict,     SCREAMING_SNAKE_CASE_						:					List[Any]   ):
										def find_re(SCREAMING_SNAKE_CASE_						:					Any,     SCREAMING_SNAKE_CASE_						:					List[str],     SCREAMING_SNAKE_CASE_						:					List[str]   ):
																snake_case							:  Any			=     pattern.search(SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_   )
																return m.start() if m else -1

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

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

										if len(SCREAMING_SNAKE_CASE_   ) > 1:
																snake_case							:  int			=     completion[: prints[1].start()]

										snake_case							:  Union[str, Any]			=     list(re.finditer('''^def''',     SCREAMING_SNAKE_CASE_,     re.MULTILINE   )   )

										if len(SCREAMING_SNAKE_CASE_   ) > 1:
																snake_case							:  Union[str, Any]			=     completion[: defs[1].start()]

										snake_case							:  Any			=     0

										snake_case							:  Union[str, Any]			=     [
										    pos for pos in [find_re(SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_   ) for terminal in terminals] if pos != -1
										]

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



from __future__ import annotations
def lowerCamelCase_       (			A			:      list[int]						):




      """simple docstring"""
      if not list_of_ints:
            return []

      if min(A						) < 0:
            raise ValueError('''All numbers must be positive'''						)

      lowerCAmelCase_						=      max(len(bin(A						)[2:]						) for x in list_of_ints						)
      return _msd_radix_sort(A		,					A						)
def lowerCamelCase_       (			A			:      list[int]		,					A			:      int						):




      """simple docstring"""
      if bit_position == 0 or len(A						) in [0, 1]:
            return list_of_ints

      lowerCAmelCase_						=      []
      lowerCAmelCase_						=      []
      # Split numbers based on bit at bit_position from the right
      for number in list_of_ints:
            if (number >> (bit_position - 1)) & 1:
                  # number has a one at bit bit_position
                  ones.append(A						)
            else:
                  # number has a zero at bit bit_position
                  zeros.append(A						)

    # recursively split both lists further
      lowerCAmelCase_						=      _msd_radix_sort(A		,					bit_position - 1						)
      lowerCAmelCase_						=      _msd_radix_sort(A		,					bit_position - 1						)

      # recombine lists
      lowerCAmelCase_						=      zeros
      res.extend(A						)

      return res
def lowerCamelCase_       (			A			:      list[int]						):




      """simple docstring"""
      lowerCAmelCase_						=      len(A						)
      if not list_of_ints or length == 1:
            return

      if min(A						) < 0:
            raise ValueError('''All numbers must be positive'''						)

      lowerCAmelCase_						=      max(len(bin(A						)[2:]						) for x in list_of_ints						)
      _msd_radix_sort_inplace(A		,					A		,					0		,					A						)
def lowerCamelCase_       (			A			:      list[int]		,					A			:      int		,					A			:      int		,					A			:      int						):




      """simple docstring"""
      if bit_position == 0 or end_index - begin_index <= 1:
            return

      bit_position -= 1

      lowerCAmelCase_						=      begin_index
      lowerCAmelCase_						=      end_index - 1
      while i <= j:
            lowerCAmelCase_						=      False
            if not (list_of_ints[i] >> bit_position) & 1:
                  # found zero at the beginning
                  i += 1
                  lowerCAmelCase_						=      True
            if (list_of_ints[j] >> bit_position) & 1:
                  # found one at the end
                  j -= 1
                  lowerCAmelCase_						=      True

            if changed:
                  continue

            lowerCAmelCase_			,		lowerCAmelCase_						=      list_of_ints[j], list_of_ints[i]
            j -= 1
            if j != i:
                  i += 1

      _msd_radix_sort_inplace(A		,					A		,					A		,					A						)
      _msd_radix_sort_inplace(A		,					A		,					A		,					A						)


if __name__ == "__main__":
 import doctest

 doctest.testmod()



