





"""simple docstring"""





import unittest
from pathlib import Path
from tempfile import TemporaryDirectory

from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available
from transformers.models.gpta.tokenization_gpta import GPTaTokenizer
from transformers.testing_utils import require_keras_nlp, require_tf, slow


if is_tf_available():
  import tensorflow as tf

if is_keras_nlp_available():
  from transformers.models.gpta import TFGPTaTokenizer


__A											=						["""gpt2"""]
__A											=						"""gpt2"""

if is_tf_available():






  class    _lowerCAmelCase  (	tf.Module			):
         """simple docstring"""




         def __init__(       self       ,					__UpperCAmelCase ):



           '''simple docstring'''

           super().__init__()
           lowerCAmelCase__     :List[str]											=				tokenizer
           lowerCAmelCase__     :Optional[int]											=				AutoConfig.from_pretrained(__UpperCAmelCase )
           lowerCAmelCase__     :Optional[Any]											=				TFGPTaLMHeadModel.from_config(__UpperCAmelCase )






         @tf.function(input_signature=(tf.TensorSpec((None,)       ,					tf.string       ,					name='text' ),) )
         def 	snake_case		(       self       ,					__UpperCAmelCase ):



           '''simple docstring'''

           lowerCAmelCase__     :str											=				self.tokenizer(__UpperCAmelCase )
           lowerCAmelCase__     :int											=				tokenized['input_ids'].to_tensor()

           lowerCAmelCase__     :Optional[Any]											=				tf.cast(input_ids_dense > 0       ,					tf.intaa )
           # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN])

           lowerCAmelCase__     :int											=				self.model(input_ids=__UpperCAmelCase       ,					attention_mask=__UpperCAmelCase )['logits']

           return outputs






@require_tf
@require_keras_nlp
class    _lowerCAmelCase  (	unittest.TestCase			):
       """simple docstring"""




       def 	snake_case		(       self ):



         '''simple docstring'''

         super().setUp()

         lowerCAmelCase__     :List[str]											=				[GPTaTokenizer.from_pretrained(__UpperCAmelCase ) for checkpoint in (TOKENIZER_CHECKPOINTS)]
         lowerCAmelCase__     :Union[str, Any]											=				[TFGPTaTokenizer.from_pretrained(__UpperCAmelCase ) for checkpoint in TOKENIZER_CHECKPOINTS]
         assert len(self.tokenizers ) == len(self.tf_tokenizers )

         lowerCAmelCase__     :int											=				[
             'This is a straightforward English test sentence.',
             'This one has some weird characters\rto\nsee\r\nif  those\u00E9break things.',
             'Now we\'re going to add some Chinese: 一 二 三 一二三',
             'And some much more rare Chinese: 齉 堃 齉堃',
             'Je vais aussi écrire en français pour tester les accents',
             'Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ',
         ]
         lowerCAmelCase__     :str											=				list(zip(self.test_sentences       ,					self.test_sentences[::-1] ) )






       def 	snake_case		(       self ):



         '''simple docstring'''

         for tokenizer, tf_tokenizer in zip(self.tokenizers       ,					self.tf_tokenizers ):
           for test_inputs in self.test_sentences:
             lowerCAmelCase__     :int											=				tokenizer([test_inputs]       ,					return_tensors='tf' )
             lowerCAmelCase__     :Optional[int]											=				tf_tokenizer([test_inputs] )

             for key in python_outputs.keys():
               # convert them to numpy to avoid messing with ragged tensors
               lowerCAmelCase__     :Optional[int]											=				python_outputs[key].numpy()
               lowerCAmelCase__     :List[str]											=				tf_outputs[key].numpy()

               self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape ) )
               self.assertTrue(tf.reduce_all(tf.cast(__UpperCAmelCase       ,					tf.intaa ) == tf_outputs_values ) )






       @slow
       def 	snake_case		(       self ):



         '''simple docstring'''

         for tf_tokenizer in self.tf_tokenizers:
           lowerCAmelCase__     :Optional[int]											=				tf.function(__UpperCAmelCase )
           for test_inputs in self.test_sentences:
             lowerCAmelCase__     :Any											=				tf.constant(__UpperCAmelCase )
             lowerCAmelCase__     :int											=				compiled_tokenizer(__UpperCAmelCase )
             lowerCAmelCase__     :Any											=				tf_tokenizer(__UpperCAmelCase )

             for key in eager_outputs.keys():
               self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) )






       @slow
       def 	snake_case		(       self ):



         '''simple docstring'''

         for tf_tokenizer in self.tf_tokenizers:
           lowerCAmelCase__     :List[str]											=				ModelToSave(tokenizer=__UpperCAmelCase )
           lowerCAmelCase__     :Union[str, Any]											=				tf.convert_to_tensor([self.test_sentences[0]] )
           lowerCAmelCase__     :List[str]											=				model.serving(__UpperCAmelCase )  # Build model with some sample inputs
           with TemporaryDirectory() as tempdir:
             lowerCAmelCase__     :Union[str, Any]											=				Path(__UpperCAmelCase ) / 'saved.model'
             tf.saved_model.save(__UpperCAmelCase       ,					__UpperCAmelCase       ,					signatures={'serving_default': model.serving} )
             lowerCAmelCase__     :str											=				tf.saved_model.load(__UpperCAmelCase )
           lowerCAmelCase__     :Dict											=				loaded_model.signatures['serving_default'](__UpperCAmelCase )['output_0']
           # We may see small differences because the loaded model is compiled, so we need an epsilon for the test
           self.assertTrue(tf.reduce_all(out == loaded_output ) )






       @slow
       def 	snake_case		(       self ):



         '''simple docstring'''

         for tf_tokenizer in self.tf_tokenizers:
           lowerCAmelCase__     :List[str]											=				tf.convert_to_tensor([self.test_sentences[0]] )
           lowerCAmelCase__     :List[str]											=				tf_tokenizer(__UpperCAmelCase )  # Build model with some sample inputs

           lowerCAmelCase__     :Union[str, Any]											=				tf_tokenizer.get_config()
           lowerCAmelCase__     :Tuple											=				TFGPTaTokenizer.from_config(__UpperCAmelCase )
           lowerCAmelCase__     :Tuple											=				model_from_config(__UpperCAmelCase )

           for key in from_config_output.keys():
             self.assertTrue(tf.reduce_all(from_config_output[key] == out[key] ) )






       @slow
       def 	snake_case		(       self ):



         '''simple docstring'''

         for tf_tokenizer in self.tf_tokenizers:
           # for the test to run
           lowerCAmelCase__     :int											=				1_2_3_1_2_3

           for max_length in [3, 5, 1_0_2_4]:
             lowerCAmelCase__     :Tuple											=				tf.convert_to_tensor([self.test_sentences[0]] )
             lowerCAmelCase__     :List[str]											=				tf_tokenizer(__UpperCAmelCase       ,					max_length=__UpperCAmelCase )

             lowerCAmelCase__     :Union[str, Any]											=				out['input_ids'].numpy().shape[1]

             assert out_length == max_length

'''simple docstring'''

import argparse
import logging
import pickle
import random
import time

import numpy as np

from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer


logging.basicConfig(
    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO
)
UpperCamelCase__  :						Dict					=      logging.getLogger(__name__)







def __UpperCamelCase( ):
   '''simple docstring'''
   UpperCAmelCase__				:					Optional[Any] 					=	argparse.ArgumentParser(
       description='''Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).'''     )
   parser.add_argument('''--file_path'''	,      type=_A	,      default='''data/dump.txt'''	,      help='''The path to the data.'''     )
   parser.add_argument('''--tokenizer_type'''	,      type=_A	,      default='''bert'''	,      choices=['''bert''', '''roberta''', '''gpt2''']     )
   parser.add_argument('''--tokenizer_name'''	,      type=_A	,      default='''bert-base-uncased'''	,      help='''The tokenizer to use.'''     )
   parser.add_argument('''--dump_file'''	,      type=_A	,      default='''data/dump'''	,      help='''The dump file prefix.'''     )
   UpperCAmelCase__				:					Optional[int] 					=	parser.parse_args()

   logger.info(F'''Loading Tokenizer ({args.tokenizer_name})'''     )
   if args.tokenizer_type == "bert":
      UpperCAmelCase__				:					List[str] 					=	BertTokenizer.from_pretrained(args.tokenizer_name     )
      UpperCAmelCase__				:					Optional[Any] 					=	tokenizer.special_tokens_map['''cls_token''']  # `[CLS]`
      UpperCAmelCase__				:					Union[str, Any] 					=	tokenizer.special_tokens_map['''sep_token''']  # `[SEP]`
   elif args.tokenizer_type == "roberta":
      UpperCAmelCase__				:					Union[str, Any] 					=	RobertaTokenizer.from_pretrained(args.tokenizer_name     )
      UpperCAmelCase__				:					List[Any] 					=	tokenizer.special_tokens_map['''cls_token''']  # `<s>`
      UpperCAmelCase__				:					Dict 					=	tokenizer.special_tokens_map['''sep_token''']  # `</s>`
   elif args.tokenizer_type == "gpt2":
      UpperCAmelCase__				:					List[str] 					=	GPTaTokenizer.from_pretrained(args.tokenizer_name     )
      UpperCAmelCase__				:					List[Any] 					=	tokenizer.special_tokens_map['''bos_token''']  # `<|endoftext|>`
      UpperCAmelCase__				:					Optional[Any] 					=	tokenizer.special_tokens_map['''eos_token''']  # `<|endoftext|>`

   logger.info(F'''Loading text from {args.file_path}'''     )
   with open(args.file_path	,      '''r'''	,      encoding='''utf8'''     ) as fp:
      UpperCAmelCase__				:					List[Any] 					=	fp.readlines()

   logger.info('''Start encoding'''     )
   logger.info(F'''{len(_A     )} examples to process.'''     )

   UpperCAmelCase__				:					List[str] 					=	[]
   UpperCAmelCase__				:					Union[str, Any] 					=	0
   UpperCAmelCase__				:					Optional[int] 					=	1_00_00
   UpperCAmelCase__				:					Tuple 					=	time.time()
   for text in data:
      UpperCAmelCase__				:					Any 					=	F'''{bos} {text.strip()} {sep}'''
      UpperCAmelCase__				:					int 					=	tokenizer.encode(_A	,      add_special_tokens=_A     )
      rslt.append(_A     )

      iter += 1
      if iter % interval == 0:
         UpperCAmelCase__				:					int 					=	time.time()
         logger.info(F'''{iter} examples processed. - {(end-start):.2f}s/{interval}expl'''     )
         UpperCAmelCase__				:					Optional[Any] 					=	time.time()
   logger.info('''Finished binarization'''     )
   logger.info(F'''{len(_A     )} examples processed.'''     )

   UpperCAmelCase__				:					Dict 					=	F'''{args.dump_file}.{args.tokenizer_name}.pickle'''
   UpperCAmelCase__				:					Dict 					=	tokenizer.vocab_size
   if vocab_size < (1 << 16):
      UpperCAmelCase__				:					Any 					=	[np.uintaa(_A     ) for d in rslt]
   else:
      UpperCAmelCase__				:					str 					=	[np.intaa(_A     ) for d in rslt]
   random.shuffle(rslt_     )
   logger.info(F'''Dump to {dp_file}'''     )
   with open(_A	,      '''wb'''     ) as handle:
      pickle.dump(rslt_	,      _A	,      protocol=pickle.HIGHEST_PROTOCOL     )


if __name__ == "__main__":
  main()




