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


lowerCAmelCase__      		=					logging.get_logger(__name__)

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

lowerCAmelCase__      		=					{
    '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',
    },
}

lowerCAmelCase__      		=					{
    'Salesforce/codegen-350M-mono': 2048,
}






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






def  __lowerCamelCase						(		lowerCAmelCase__      ):
       lowerCAmelCase__	      =   set()
       lowerCAmelCase__	      =   word[0]
       for char in word[1:]:
              pairs.add((prev_char, char)      )
              lowerCAmelCase__	      =   char
       return pairs



class 							a_					(		SCREAMING_SNAKE_CASE		):






 '''simple docstring'''






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




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







        '''simple docstring'''



        lowerCAmelCase__	      =   AddedToken(lowercase__     ,       lstrip=lowercase__     ,       rstrip=lowercase__) if isinstance(lowercase__     ,       lowercase__) else bos_token
        lowerCAmelCase__	      =   AddedToken(lowercase__     ,       lstrip=lowercase__     ,       rstrip=lowercase__) if isinstance(lowercase__     ,       lowercase__) else eos_token
        lowerCAmelCase__	      =   AddedToken(lowercase__     ,       lstrip=lowercase__     ,       rstrip=lowercase__) if isinstance(lowercase__     ,       lowercase__) else unk_token
        lowerCAmelCase__	      =   AddedToken(lowercase__     ,       lstrip=lowercase__     ,       rstrip=lowercase__) if isinstance(lowercase__     ,       lowercase__) else pad_token
        super().__init__(
            errors=lowercase__     ,       unk_token=lowercase__     ,       bos_token=lowercase__     ,       eos_token=lowercase__     ,       pad_token=lowercase__     ,       add_prefix_space=lowercase__     ,       add_bos_token=lowercase__     ,       **lowercase__     ,       )
        lowerCAmelCase__	      =   add_bos_token

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

        # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
        lowerCAmelCase__	      =   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   :    Dict):







        '''simple docstring'''



        return len(self.encoder)




 def 						__snake_case		(     self   :    str):







        '''simple docstring'''



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




 def 						__snake_case		(     self   :    Any     ,       lowercase__   :    Optional[int]):







        '''simple docstring'''



        if token in self.cache:
               return self.cache[token]
        lowerCAmelCase__	      =   tuple(lowercase__)
        lowerCAmelCase__	      =   get_pairs(lowercase__)

        if not pairs:
               return token

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

                      if word[i] == first and i < len(lowercase__) - 1 and word[i + 1] == second:
                             new_word.append(first + second)
                             i += 2
                      else:
                             new_word.append(word[i])
                             i += 1
               lowerCAmelCase__	      =   tuple(lowercase__)
               lowerCAmelCase__	      =   new_word
               if len(lowercase__) == 1:
                      break
               else:
                      lowerCAmelCase__	      =   get_pairs(lowercase__)
        lowerCAmelCase__	      =   ' '.join(lowercase__)
        lowerCAmelCase__	      =   word
        return word




 def 						__snake_case		(     self   :    List[str]     ,       lowercase__   :    Optional[int]     ,       lowercase__   :    List[Any]=None):







        '''simple docstring'''



        if self.add_bos_token:
               lowerCAmelCase__	      =   [self.bos_token_id]
        else:
               lowerCAmelCase__	      =   []

        lowerCAmelCase__	      =   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   :    int     ,       lowercase__   :    Dict):







        '''simple docstring'''



        lowerCAmelCase__	      =   []
        for token in re.findall(self.pat     ,       lowercase__):
               lowerCAmelCase__	      =   ''.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(lowercase__).split(' '))
        return bpe_tokens




 def 						__snake_case		(     self   :    Optional[Any]     ,       lowercase__   :    List[Any]):







        '''simple docstring'''



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




 def 						__snake_case		(     self   :    List[str]     ,       lowercase__   :    List[str]):







        '''simple docstring'''



        return self.decoder.get(lowercase__)




 def 						__snake_case		(     self   :    int     ,       lowercase__   :    List[Any]):







        '''simple docstring'''



        lowerCAmelCase__	      =   ''.join(lowercase__)
        lowerCAmelCase__	      =   bytearray([self.byte_decoder[c] for c in text]).decode('utf-8'     ,       errors=self.errors)
        return text




 def 						__snake_case		(     self   :    List[Any]     ,       lowercase__   :    str     ,       lowercase__   :    Optional[str] = None):







        '''simple docstring'''



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

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

        lowerCAmelCase__	      =   0
        with open(lowercase__     ,       '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 lowercase__: 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__	      =   token_index
                      writer.write(' '.join(lowercase__) + '\n')
                      index += 1

        return vocab_file, merge_file




 def 						__snake_case		(     self   :    Dict     ,       lowercase__   :    Dict     ,       lowercase__   :    List[str]=False     ,       **lowercase__   :    int):







        '''simple docstring'''



        lowerCAmelCase__	      =   kwargs.pop('add_prefix_space'     ,       self.add_prefix_space)
        if is_split_into_words or add_prefix_space:
               lowerCAmelCase__	      =   ' ' + text
        return (text, kwargs)




 def 						__snake_case		(     self   :    Union[str, Any]     ,       lowercase__   :    Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"]     ,       lowercase__   :    bool = False     ,       lowercase__   :    bool = None     ,       lowercase__   :    Optional[List[str]] = None     ,       **lowercase__   :    Optional[int]     ,       ):







        '''simple docstring'''



        lowerCAmelCase__	      =   super()._decode(
            token_ids=lowercase__     ,       skip_special_tokens=lowercase__     ,       clean_up_tokenization_spaces=lowercase__     ,       **lowercase__     ,       )

        if truncate_before_pattern is not None and len(lowercase__) > 0:
               lowerCAmelCase__	      =   self.truncate(lowercase__     ,       lowercase__)

        return decoded_text




 def 						__snake_case		(     self   :    Dict     ,       lowercase__   :    Tuple     ,       lowercase__   :    Dict):







        '''simple docstring'''



        def find_re(lowercase__   :    Optional[int]     ,       lowercase__   :    int     ,       lowercase__   :    int):
               lowerCAmelCase__	      =   pattern.search(lowercase__     ,       lowercase__)
               return m.start() if m else -1

        lowerCAmelCase__	      =   [re.compile(lowercase__     ,       re.MULTILINE) for pattern in truncate_before_pattern]

        lowerCAmelCase__	      =   list(re.finditer('^print'     ,       lowercase__     ,       re.MULTILINE))

        if len(lowercase__) > 1:
               lowerCAmelCase__	      =   completion[: prints[1].start()]

        lowerCAmelCase__	      =   list(re.finditer('^def'     ,       lowercase__     ,       re.MULTILINE))

        if len(lowercase__) > 1:
               lowerCAmelCase__	      =   completion[: defs[1].start()]

        lowerCAmelCase__	      =   0

        lowerCAmelCase__	      =   [
            pos for pos in [find_re(lowercase__     ,       lowercase__     ,       lowercase__) for terminal in terminals] if pos != -1
        ]

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

def  __lowerCamelCase						(		lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      ):
       if hue < 0 or hue > 3_6_0:
              raise Exception('hue should be between 0 and 360'      )

       if saturation < 0 or saturation > 1:
              raise Exception('saturation should be between 0 and 1'      )

       if value < 0 or value > 1:
              raise Exception('value should be between 0 and 1'      )

       lowerCAmelCase__	      =   value * saturation
       lowerCAmelCase__	      =   hue / 6_0
       lowerCAmelCase__	      =   chroma * (1 - abs(hue_section % 2 - 1      ))
       lowerCAmelCase__	      =   value - chroma

       if hue_section >= 0 and hue_section <= 1:
              lowerCAmelCase__	      =   round(2_5_5 * (chroma + match_value)      )
              lowerCAmelCase__	      =   round(2_5_5 * (second_largest_component + match_value)      )
              lowerCAmelCase__	      =   round(2_5_5 * (match_value)      )
       elif hue_section > 1 and hue_section <= 2:
              lowerCAmelCase__	      =   round(2_5_5 * (second_largest_component + match_value)      )
              lowerCAmelCase__	      =   round(2_5_5 * (chroma + match_value)      )
              lowerCAmelCase__	      =   round(2_5_5 * (match_value)      )
       elif hue_section > 2 and hue_section <= 3:
              lowerCAmelCase__	      =   round(2_5_5 * (match_value)      )
              lowerCAmelCase__	      =   round(2_5_5 * (chroma + match_value)      )
              lowerCAmelCase__	      =   round(2_5_5 * (second_largest_component + match_value)      )
       elif hue_section > 3 and hue_section <= 4:
              lowerCAmelCase__	      =   round(2_5_5 * (match_value)      )
              lowerCAmelCase__	      =   round(2_5_5 * (second_largest_component + match_value)      )
              lowerCAmelCase__	      =   round(2_5_5 * (chroma + match_value)      )
       elif hue_section > 4 and hue_section <= 5:
              lowerCAmelCase__	      =   round(2_5_5 * (second_largest_component + match_value)      )
              lowerCAmelCase__	      =   round(2_5_5 * (match_value)      )
              lowerCAmelCase__	      =   round(2_5_5 * (chroma + match_value)      )
       else:
              lowerCAmelCase__	      =   round(2_5_5 * (chroma + match_value)      )
              lowerCAmelCase__	      =   round(2_5_5 * (match_value)      )
              lowerCAmelCase__	      =   round(2_5_5 * (second_largest_component + match_value)      )

       return [red, green, blue]






def  __lowerCamelCase						(		lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      ):
       if red < 0 or red > 2_5_5:
              raise Exception('red should be between 0 and 255'      )

       if green < 0 or green > 2_5_5:
              raise Exception('green should be between 0 and 255'      )

       if blue < 0 or blue > 2_5_5:
              raise Exception('blue should be between 0 and 255'      )

       lowerCAmelCase__	      =   red / 2_5_5
       lowerCAmelCase__	      =   green / 2_5_5
       lowerCAmelCase__	      =   blue / 2_5_5
       lowerCAmelCase__	      =   max(lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      )
       lowerCAmelCase__	      =   value - min(lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      )
       lowerCAmelCase__	      =   0 if value == 0 else chroma / value

       if chroma == 0:
              lowerCAmelCase__	      =   0.0
       elif value == float_red:
              lowerCAmelCase__	      =   6_0 * (0 + (float_green - float_blue) / chroma)
       elif value == float_green:
              lowerCAmelCase__	      =   6_0 * (2 + (float_blue - float_red) / chroma)
       else:
              lowerCAmelCase__	      =   6_0 * (4 + (float_red - float_green) / chroma)

       lowerCAmelCase__	      =   (hue + 3_6_0) % 3_6_0

       return [hue, saturation, value]






def  __lowerCamelCase						(		lowerCAmelCase__      ,    lowerCAmelCase__      ):
       lowerCAmelCase__	      =   abs(hsv_a[0] - hsv_a[0]      ) < 0.2
       lowerCAmelCase__	      =   abs(hsv_a[1] - hsv_a[1]      ) < 0.0_0_2
       lowerCAmelCase__	      =   abs(hsv_a[2] - hsv_a[2]      ) < 0.0_0_2

       return check_hue and check_saturation and check_value
