






"""simple docstring"""


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

from tokenizers import pre_tokenizers

from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_gpta import GPTaTokenizer


if TYPE_CHECKING:
		from transformers.pipelines.conversational import Conversation


__SCREAMING_SNAKE_CASE   =   logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE   =   {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'}

__SCREAMING_SNAKE_CASE   =   {
    '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',
    },
    'tokenizer_file': {
        'gpt2': 'https://huggingface.co/gpt2/resolve/main/tokenizer.json',
        'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json',
        'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/tokenizer.json',
        'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json',
        'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/tokenizer.json',
    },
}

__SCREAMING_SNAKE_CASE   =   {
    'gpt2': 10_24,
    'gpt2-medium': 10_24,
    'gpt2-large': 10_24,
    'gpt2-xl': 10_24,
    'distilgpt2': 10_24,
}




class 						__UpperCamelCase     (     __SCREAMING_SNAKE_CASE						):
					lowercase_    :				Union[str, Any]      =  VOCAB_FILES_NAMES
					lowercase_    :				Any      =  PRETRAINED_VOCAB_FILES_MAP
					lowercase_    :				Optional[Any]      =  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
					lowercase_    :				Union[str, Any]      =  ['''input_ids''', '''attention_mask''']
					lowercase_    :				Tuple      =  GPTaTokenizer
					def __init__(							self							:	Optional[int]     , UpperCAmelCase							:	str=None     , UpperCAmelCase							:	Union[str, Any]=None     , UpperCAmelCase							:	Union[str, Any]=None     , UpperCAmelCase							:	List[str]="<|endoftext|>"     , UpperCAmelCase							:	Dict="<|endoftext|>"     , UpperCAmelCase							:	Union[str, Any]="<|endoftext|>"     , UpperCAmelCase							:	List[str]=False     , **UpperCAmelCase							:	Any     , )	->       List[str]:
											super().__init__(
											    __lowerCamelCase     , __lowerCamelCase     , tokenizer_file=__lowerCamelCase     , unk_token=__lowerCamelCase     , bos_token=__lowerCamelCase     , eos_token=__lowerCamelCase     , add_prefix_space=__lowerCamelCase     , **__lowerCamelCase     , )

											lowerCAmelCase   :Dict						=			kwargs.pop('add_bos_token'     , __lowerCamelCase   )

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

											lowerCAmelCase   :Optional[Any]						=			add_prefix_space
					def        UpperCAmelCase__ (							self							:	Optional[int]     , *UpperCAmelCase							:	Optional[int]     , **UpperCAmelCase							:	Union[str, Any]   )	->       List[str]:
											lowerCAmelCase   :int						=			kwargs.get('is_split_into_words'     , __lowerCamelCase   )
											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(*__lowerCamelCase     , **__lowerCamelCase   )
					def        UpperCAmelCase__ (							self							:	Tuple     , *UpperCAmelCase							:	Any     , **UpperCAmelCase							:	str   )	->       int:
											lowerCAmelCase   :List[Any]						=			kwargs.get('is_split_into_words'     , __lowerCamelCase   )

											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(*__lowerCamelCase     , **__lowerCamelCase   )
					def        UpperCAmelCase__ (							self							:	Optional[Any]     , UpperCAmelCase							:	str     , UpperCAmelCase							:	Optional[str] = None   )	->       Optional[Any]:
											lowerCAmelCase   :List[str]						=			self._tokenizer.model.save(__lowerCamelCase     , name=__lowerCamelCase   )
											return tuple(__lowerCamelCase   )
					def        UpperCAmelCase__ (							self							:	Tuple     , UpperCAmelCase							:	"Conversation"   )	->       Optional[Any]:
											lowerCAmelCase   :str						=			[]
											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   :List[str]						=			input_ids[-self.model_max_length :]
											return input_ids




"""simple docstring"""






import collections
import os
from typing import List, Optional, Tuple

from transformers.utils import is_jieba_available, requires_backends


if is_jieba_available():
     import jieba

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


snake_case   					=				logging.get_logger(__name__)

snake_case   					=				{'''vocab_file''': '''vocab.txt'''}

snake_case   					=				{
    '''vocab_file''': {
        '''openbmb/cpm-ant-10b''': '''https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt''',
    },
}

snake_case   					=				{
    '''openbmb/cpm-ant-10b''': 1_0_2_4,
}




def 			snake_case		(		lowerCAmelCase_	)						->				int:
  _snake_case   	=      collections.OrderedDict()
  with open(lowerCAmelCase_  ,						'''r'''  ,						encoding='''utf-8'''	) as reader:
    _snake_case   	=      reader.readlines()
  for index, token in enumerate(lowerCAmelCase_	):
    _snake_case   	=      token.rstrip('''\n'''	)
    _snake_case   	=      index
  return vocab



class     UpperCAmelCase    (	__SCREAMING_SNAKE_CASE  ):



   def __init__(       self    :	Union[str, Any]							,       __lowerCamelCase    :	int							,       __lowerCamelCase    :	List[str]="<unk>"							,       __lowerCamelCase    :	Tuple=2_0_0				):



     """simple docstring"""
     _snake_case   	=      vocab
     _snake_case   	=      unk_token
     _snake_case   	=      max_input_chars_per_word





   def    __UpperCAmelCase    (       self    :	Any							,       __lowerCamelCase    :	str				):



     """simple docstring"""
     _snake_case   	=      list(__lowerCamelCase				)
     if len(__lowerCamelCase				) > self.max_input_chars_per_word:
       return [self.unk_token]

     _snake_case   	=      0
     _snake_case   	=      []
     while start < len(__lowerCamelCase				):
       _snake_case   	=      len(__lowerCamelCase				)
       _snake_case   	=      None
       while start < end:
         _snake_case   	=      ''''''.join(chars[start:end]				)
         if substr in self.vocab:
           _snake_case   	=      substr
           break
         end -= 1
       if cur_substr is None:
         sub_tokens.append(self.unk_token				)
         start += 1
       else:
         sub_tokens.append(__lowerCamelCase				)
         _snake_case   	=      end

     return sub_tokens



class     UpperCAmelCase    (	__SCREAMING_SNAKE_CASE  ):
   A__		:	List[str]           =  VOCAB_FILES_NAMES
   A__		:	str           =  PRETRAINED_VOCAB_FILES_MAP
   A__		:	str           =  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   A__		:	Union[str, Any]           =  ['''input_ids''', '''attention_mask''']
   A__		:	Optional[int]           =  False



   def __init__(       self    :	Dict							,       __lowerCamelCase    :	Optional[Any]							,       __lowerCamelCase    :	str="<d>"							,       __lowerCamelCase    :	Tuple="</d>"							,       __lowerCamelCase    :	Tuple="<s>"							,       __lowerCamelCase    :	int="</s>"							,       __lowerCamelCase    :	List[str]="<pad>"							,       __lowerCamelCase    :	int="<unk>"							,       __lowerCamelCase    :	int="</n>"							,       __lowerCamelCase    :	Tuple="</_>"							,       __lowerCamelCase    :	Optional[Any]="left"							,       **__lowerCamelCase    :	str							,       ):



     """simple docstring"""
     requires_backends(self							,       ['''jieba''']				)
     super().__init__(
         bod_token=__lowerCamelCase							,       eod_token=__lowerCamelCase							,       bos_token=__lowerCamelCase							,       eos_token=__lowerCamelCase							,       pad_token=__lowerCamelCase							,       unk_token=__lowerCamelCase							,       line_token=__lowerCamelCase							,       space_token=__lowerCamelCase							,       padding_side=__lowerCamelCase							,       **__lowerCamelCase							,       )
     _snake_case   	=      bod_token
     _snake_case   	=      eod_token
     _snake_case   	=      load_vocab(__lowerCamelCase				)
     _snake_case   	=      self.encoder[space_token]
     _snake_case   	=      self.encoder[line_token]

     del self.encoder[space_token]
     del self.encoder[line_token]

     _snake_case   	=      collections.OrderedDict(sorted(self.encoder.items()							,       key=lambda __lowerCamelCase				: x[1]				)				)
     _snake_case   	=      {v: k for k, v in self.encoder.items()}

     _snake_case   	=      WordpieceTokenizer(vocab=self.encoder							,       unk_token=self.unk_token				)



   @property
   def    __UpperCAmelCase    (       self    :	List[Any]				):



     """simple docstring"""
     return self.encoder[self.bod_token]



   @property
   def    __UpperCAmelCase    (       self    :	Any				):



     """simple docstring"""
     return self.encoder[self.eod_token]



   @property
   def    __UpperCAmelCase    (       self    :	Union[str, Any]				):



     """simple docstring"""
     return self.encoder["\n"]



   @property
   def    __UpperCAmelCase    (       self    :	Optional[Any]				):



     """simple docstring"""
     return len(self.encoder				)



   def    __UpperCAmelCase    (       self    :	Any				):



     """simple docstring"""
     return dict(self.encoder							,       **self.added_tokens_encoder				)



   def    __UpperCAmelCase    (       self    :	Optional[Any]							,       __lowerCamelCase    :	Optional[int]				):



     """simple docstring"""
     _snake_case   	=      []
     for x in jieba.cut(__lowerCamelCase							,       cut_all=__lowerCamelCase				):
       output_tokens.extend(self.wordpiece_tokenizer.tokenize(__lowerCamelCase				)				)
     return output_tokens



   def    __UpperCAmelCase    (       self    :	Optional[Any]							,       __lowerCamelCase    :	Union[str, Any]							,       **__lowerCamelCase    :	Optional[Any]				):



     """simple docstring"""
     _snake_case   	=      [i for i in token_ids if i >= 0]
     _snake_case   	=      [
         x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id
     ]
     return super()._decode(__lowerCamelCase							,       **__lowerCamelCase				)



   def    __UpperCAmelCase    (       self    :	Dict							,       __lowerCamelCase    :	Union[str, Any]				):



     """simple docstring"""
     return token in self.encoder



   def    __UpperCAmelCase    (       self    :	Tuple							,       __lowerCamelCase    :	List[str]				):



     """simple docstring"""
     return "".join(__lowerCamelCase				)



   def    __UpperCAmelCase    (       self    :	Dict							,       __lowerCamelCase    :	int				):



     """simple docstring"""
     return self.encoder.get(__lowerCamelCase							,       self.encoder.get(self.unk_token				)				)



   def    __UpperCAmelCase    (       self    :	Optional[Any]							,       __lowerCamelCase    :	int				):



     """simple docstring"""
     return self.decoder.get(__lowerCamelCase							,       self.unk_token				)



   def    __UpperCAmelCase    (       self    :	Tuple							,       __lowerCamelCase    :	str							,       __lowerCamelCase    :	Optional[str] = None				):



     """simple docstring"""
     if os.path.isdir(__lowerCamelCase				):
       _snake_case   	=      os.path.join(
           __lowerCamelCase							,       (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']				)
     else:
       _snake_case   	=      (filename_prefix + '''-''' if filename_prefix else '''''') + save_directory
     _snake_case   	=      0
     if " " in self.encoder:
       _snake_case   	=      self.encoder[''' ''']
       del self.encoder[" "]
     if "\n" in self.encoder:
       _snake_case   	=      self.encoder['''\n''']
       del self.encoder["\n"]
     _snake_case   	=      collections.OrderedDict(sorted(self.encoder.items()							,       key=lambda __lowerCamelCase				: x[1]				)				)
     with open(__lowerCamelCase							,       '''w'''							,       encoding='''utf-8'''				) as writer:
       for token, token_index in self.encoder.items():
         if index != token_index:
           logger.warning(
               f"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."""
               ''' Please check that the vocabulary is not corrupted!'''				)
           _snake_case   	=      token_index
         writer.write(token + '''\n'''				)
         index += 1
     return (vocab_file,)



   def    __UpperCAmelCase    (       self    :	List[str]							,       __lowerCamelCase    :	List[int]							,       __lowerCamelCase    :	List[int] = None				):



     """simple docstring"""
     if token_ids_a is None:
       return [self.bos_token_id] + token_ids_a
     return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a





   def    __UpperCAmelCase    (       self    :	str							,       __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 token_ids_a is not None:
       return [1] + ([0] * len(__lowerCamelCase				)) + [1] + ([0] * len(__lowerCamelCase				))
     return [1] + ([0] * len(__lowerCamelCase				))





