


import json
import re
from typing import TYPE_CHECKING, List, Optional, Tuple, Union

import numpy as np

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 tokenizers import pre_tokenizers

from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from .tokenization_codegen import CodeGenTokenizer


lowercase_    		=     logging.get_logger(__name__)

lowercase_    		=     {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""}

lowercase_    		=     {
    """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""",
    },
    """tokenizer_file""": {
        """Salesforce/codegen-350M-mono""": (
            """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/tokenizer.json"""
        ),
    },
}

lowercase_    		=     {
    """Salesforce/codegen-350M-mono""": 20_48,
}




class        _UpperCamelCase			(   SCREAMING_SNAKE_CASE_						):







							'''simple docstring'''
							_A						=	VOCAB_FILES_NAMES
							_A						=	PRETRAINED_VOCAB_FILES_MAP
							_A						=	PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							_A						=	["input_ids", "attention_mask"]
							_A						=	CodeGenTokenizer







							def __init__(		self	:					Optional[int]		,					SCREAMING_SNAKE_CASE_	:					Union[str, Any]=None		,					SCREAMING_SNAKE_CASE_	:					List[Any]=None		,					SCREAMING_SNAKE_CASE_	:					Any=None		,					SCREAMING_SNAKE_CASE_	:					List[str]="<|endoftext|>"		,					SCREAMING_SNAKE_CASE_	:					List[Any]="<|endoftext|>"		,					SCREAMING_SNAKE_CASE_	:					List[Any]="<|endoftext|>"		,					SCREAMING_SNAKE_CASE_	:					int=False		,					**SCREAMING_SNAKE_CASE_	:					List[Any]		,					):
													super().__init__(
													    snake_case__		,					snake_case__		,					tokenizer_file=snake_case__		,					unk_token=snake_case__		,					bos_token=snake_case__		,					eos_token=snake_case__		,					add_prefix_space=snake_case__		,					**snake_case__		,					)

													if kwargs.pop('add_bos_token'		,					snake_case__		):
																			_a     			=      kwargs.pop('name_or_path'		,					''		)
																			raise ValueError(
																			    'Currenty GPT2\'s fast tokenizer does NOT support adding a BOS token.'
																			    'Instead you should use GPT2\'s slow tokenizer class `CodeGenTokenizer` as follows: \n'
																			    f"""`CodeGenTokenizer.from_pretrained(\'{model_id}\')`\nor\n"""
																			    f"""`AutoTokenizer.from_pretrained(\'{model_id}\', use_fast=False)`\n"""
																			    'This issue will be fixed soon, see: https://github.com/huggingface/tokenizers/pull/1005.'
																			    ' so that the fast tokenizer works correctly.'		)

													_a     			=      json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()		)
													if pre_tok_state.get('add_prefix_space'		,					snake_case__		) != add_prefix_space:
																			_a     			=      getattr(snake_case__		,					pre_tok_state.pop('type'		)		)
																			_a     			=      add_prefix_space
																			_a     			=      pre_tok_class(**snake_case__		)

													_a     			=      add_prefix_space







							def 		_UpperCAmelCase						(		self	:					Optional[Any]		,					*SCREAMING_SNAKE_CASE_	:					List[Any]		,					**SCREAMING_SNAKE_CASE_	:					List[Any]		):
													_a     			=      kwargs.get('is_split_into_words'		,					snake_case__		)
													assert self.add_prefix_space or not is_split_into_words, (
													    f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
													    "to use it with pretokenized inputs."
													)

													return super()._batch_encode_plus(*snake_case__		,					**snake_case__		)







							def 		_UpperCAmelCase						(		self	:					Union[str, Any]		,					*SCREAMING_SNAKE_CASE_	:					str		,					**SCREAMING_SNAKE_CASE_	:					List[Any]		):
													_a     			=      kwargs.get('is_split_into_words'		,					snake_case__		)

													assert self.add_prefix_space or not is_split_into_words, (
													    f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
													    "to use it with pretokenized inputs."
													)

													return super()._encode_plus(*snake_case__		,					**snake_case__		)







							def 		_UpperCAmelCase						(		self	:					int		,					SCREAMING_SNAKE_CASE_	:					Tuple		,					SCREAMING_SNAKE_CASE_	:					Union[str, Any] = None		):
													_a     			=      self._tokenizer.model.save(snake_case__		,					name=snake_case__		)
													return tuple(snake_case__		)







							def 		_UpperCAmelCase						(		self	:					Union[str, Any]		,					SCREAMING_SNAKE_CASE_	:					List[str]		,					SCREAMING_SNAKE_CASE_	:					Optional[Any] = False		,					SCREAMING_SNAKE_CASE_	:					Dict = None		,					SCREAMING_SNAKE_CASE_	:					Dict = None		,					**SCREAMING_SNAKE_CASE_	:					Optional[Any]		,					):
													_a     			=      super().decode(
													    token_ids=snake_case__		,					skip_special_tokens=snake_case__		,					clean_up_tokenization_spaces=snake_case__		,					**snake_case__		,					)

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

													return decoded_text







							def 		_UpperCAmelCase						(		self	:					Optional[int]		,					SCREAMING_SNAKE_CASE_	:					Optional[Any]		,					SCREAMING_SNAKE_CASE_	:					Optional[Any]		):

													def find_re(SCREAMING_SNAKE_CASE_	:					Tuple		,					SCREAMING_SNAKE_CASE_	:					Tuple		,					SCREAMING_SNAKE_CASE_	:					int		):
																			_a     			=      pattern.search(snake_case__		,					snake_case__		)
																			return m.start() if m else -1

													_a     			=      [re.compile(snake_case__		,					re.MULTILINE		) for pattern in truncate_before_pattern]

													_a     			=      list(re.finditer('^print'		,					snake_case__		,					re.MULTILINE		)		)

													if len(snake_case__		) > 1:
																			_a     			=      completion[: prints[1].start()]

													_a     			=      list(re.finditer('^def'		,					snake_case__		,					re.MULTILINE		)		)

													if len(snake_case__		) > 1:
																			_a     			=      completion[: defs[1].start()]

													_a     			=      0

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

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






'''simple docstring'''







import json
import re
from typing import TYPE_CHECKING, List, Optional, Tuple, Union

import numpy as np

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 tokenizers import pre_tokenizers

from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from .tokenization_codegen import CodeGenTokenizer


lowerCAmelCase     :  Optional[int]											=    logging.get_logger(__name__)

lowerCAmelCase     :  Union[str, Any]											=    {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""}

lowerCAmelCase     :  Optional[Any]											=    {
    """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""",
    },
    """tokenizer_file""": {
        """Salesforce/codegen-350M-mono""": (
            """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/tokenizer.json"""
        ),
    },
}

lowerCAmelCase     :  List[str]											=    {
    """Salesforce/codegen-350M-mono""": 20_48,
}
class 						UpperCamelCase__       (			SCREAMING_SNAKE_CASE_						):



     """simple docstring"""






     __magic_name__           =     VOCAB_FILES_NAMES
     __magic_name__           =     PRETRAINED_VOCAB_FILES_MAP
     __magic_name__           =     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     __magic_name__           =     ["input_ids", "attention_mask"]
     __magic_name__           =     CodeGenTokenizer







     def __init__(			self   ,						snake_case__=None   ,						snake_case__=None   ,						snake_case__=None   ,						snake_case__="<|endoftext|>"   ,						snake_case__="<|endoftext|>"   ,						snake_case__="<|endoftext|>"   ,						snake_case__=False   ,						**snake_case__   ,						):

            '''simple docstring'''

            super().__init__(
                snake_case__   ,						snake_case__   ,						tokenizer_file=snake_case__   ,						unk_token=snake_case__   ,						bos_token=snake_case__   ,						eos_token=snake_case__   ,						add_prefix_space=snake_case__   ,						**snake_case__   ,						)

            if kwargs.pop('add_bos_token'   ,						snake_case__ ):
                   _lowerCAmelCase     :				Tuple       =							kwargs.pop('name_or_path'   ,						'' )
                   raise ValueError(
                       'Currenty GPT2\'s fast tokenizer does NOT support adding a BOS token.'
                       'Instead you should use GPT2\'s slow tokenizer class `CodeGenTokenizer` as follows: \n'
                       F'`CodeGenTokenizer.from_pretrained(\'{model_id}\')`\nor\n'
                       F'`AutoTokenizer.from_pretrained(\'{model_id}\', use_fast=False)`\n'
                       'This issue will be fixed soon, see: https://github.com/huggingface/tokenizers/pull/1005.'
                       ' so that the fast tokenizer works correctly.' )

            _lowerCAmelCase     :				List[str]       =							json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
            if pre_tok_state.get('add_prefix_space'   ,						snake_case__ ) != add_prefix_space:
                   _lowerCAmelCase     :				List[Any]       =							getattr(snake_case__   ,						pre_tok_state.pop('type' ) )
                   _lowerCAmelCase     :				Dict       =							add_prefix_space
                   _lowerCAmelCase     :				List[Any]       =							pre_tok_class(**snake_case__ )

            _lowerCAmelCase     :				Tuple       =							add_prefix_space







     def a						(			self   ,						*snake_case__   ,						**snake_case__ ):

            '''simple docstring'''

            _lowerCAmelCase     :				Union[str, Any]       =							kwargs.get('is_split_into_words'   ,						snake_case__ )
            assert self.add_prefix_space or not is_split_into_words, (
                F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True '
                "to use it with pretokenized inputs."
            )

            return super()._batch_encode_plus(*snake_case__   ,						**snake_case__ )







     def a						(			self   ,						*snake_case__   ,						**snake_case__ ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							kwargs.get('is_split_into_words'   ,						snake_case__ )

            assert self.add_prefix_space or not is_split_into_words, (
                F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True '
                "to use it with pretokenized inputs."
            )

            return super()._encode_plus(*snake_case__   ,						**snake_case__ )







     def a						(			self   ,						snake_case__   ,						snake_case__ = None ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							self._tokenizer.model.save(snake_case__   ,						name=snake_case__ )
            return tuple(snake_case__ )







     def a						(			self   ,						snake_case__   ,						snake_case__ = False   ,						snake_case__ = None   ,						snake_case__ = None   ,						**snake_case__   ,						):

            '''simple docstring'''

            _lowerCAmelCase     :				Dict       =							super().decode(
                token_ids=snake_case__   ,						skip_special_tokens=snake_case__   ,						clean_up_tokenization_spaces=snake_case__   ,						**snake_case__   ,						)

            if truncate_before_pattern is not None and len(snake_case__ ) > 0:
                   _lowerCAmelCase     :				Optional[int]       =							self.truncate(snake_case__   ,						snake_case__ )

            return decoded_text







     def a						(			self   ,						snake_case__   ,						snake_case__ ):

            '''simple docstring'''

            def find_re(snake_case__   ,						snake_case__   ,						snake_case__ ):
                   _lowerCAmelCase     :				List[Any]       =							pattern.search(snake_case__   ,						snake_case__ )
                   return m.start() if m else -1

            _lowerCAmelCase     :				Any       =							[re.compile(snake_case__   ,						re.MULTILINE ) for pattern in truncate_before_pattern]

            _lowerCAmelCase     :				Dict       =							list(re.finditer('^print'   ,						snake_case__   ,						re.MULTILINE ) )

            if len(snake_case__ ) > 1:
                   _lowerCAmelCase     :				Optional[int]       =							completion[: prints[1].start()]

            _lowerCAmelCase     :				Optional[int]       =							list(re.finditer('^def'   ,						snake_case__   ,						re.MULTILINE ) )

            if len(snake_case__ ) > 1:
                   _lowerCAmelCase     :				Optional[Any]       =							completion[: defs[1].start()]

            _lowerCAmelCase     :				int       =							0

            _lowerCAmelCase     :				Tuple       =							[
                pos for pos in [find_re(snake_case__   ,						snake_case__   ,						snake_case__ ) for terminal in terminals] if pos != -1
            ]

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

