




'''simple docstring'''


import pytest

from datasets.splits import SplitDict, SplitInfo
from datasets.utils.py_utils import asdict
@pytest.mark.parametrize(
    '''split_dict'''					,		[
        SplitDict(),
        SplitDict({'''train''': SplitInfo(name='''train'''					,		num_bytes=1337					,		num_examples=42					,		dataset_name='''my_dataset''' )} ),
        SplitDict({'''train''': SplitInfo(name='''train'''					,		num_bytes=1337					,		num_examples=42 )} ),
        SplitDict({'''train''': SplitInfo()} ),
    ]					,		)
def 						snake_case_       (UpperCamelCase			:    SplitDict ):





							'''simple docstring'''


							_a      	=							split_dict._to_yaml_list()
							assert len(UpperCamelCase ) == len(UpperCamelCase )
							_a      	=							SplitDict._from_yaml_list(UpperCamelCase )
							for split_name, split_info in split_dict.items():
														# dataset_name field is deprecated, and is therefore not part of the YAML dump
														_a      	=							None
														# the split name of split_dict takes over the name of the split info object
														_a      	=							split_name
							assert split_dict == reloaded

@pytest.mark.parametrize(
    '''split_info'''					,		[SplitInfo(), SplitInfo(dataset_name=UpperCamelCase ), SplitInfo(dataset_name='''my_dataset''' )] )
def 						snake_case_       (UpperCamelCase			:    List[str] ):





							'''simple docstring'''


							_a      	=							asdict(SplitDict({'''train''': split_info} ) )
							assert "dataset_name" in split_dict_asdict["train"]
							assert split_dict_asdict["train"]["dataset_name"] == split_info.dataset_name








'''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
)
A__							:  List[str]    =logging.getLogger(__name__)
def   UpperCamelCase__ (						):





      """simple docstring"""


      _lowerCAmelCase					=				argparse.ArgumentParser(
          description="""Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids)."""    )
      parser.add_argument("""--file_path"""				,      type=lowerCAmelCase				,      default="""data/dump.txt"""				,      help="""The path to the data."""    )
      parser.add_argument("""--tokenizer_type"""				,      type=lowerCAmelCase				,      default="""bert"""				,      choices=["""bert""", """roberta""", """gpt2"""]    )
      parser.add_argument("""--tokenizer_name"""				,      type=lowerCAmelCase				,      default="""bert-base-uncased"""				,      help="""The tokenizer to use."""    )
      parser.add_argument("""--dump_file"""				,      type=lowerCAmelCase				,      default="""data/dump"""				,      help="""The dump file prefix."""    )
      _lowerCAmelCase					=				parser.parse_args()

      logger.info(f"Loading Tokenizer ({args.tokenizer_name})"    )
      if args.tokenizer_type == "bert":
            _lowerCAmelCase					=				BertTokenizer.from_pretrained(args.tokenizer_name    )
            _lowerCAmelCase					=				tokenizer.special_tokens_map["""cls_token"""]  # `[CLS]`
            _lowerCAmelCase					=				tokenizer.special_tokens_map["""sep_token"""]  # `[SEP]`
      elif args.tokenizer_type == "roberta":
            _lowerCAmelCase					=				RobertaTokenizer.from_pretrained(args.tokenizer_name    )
            _lowerCAmelCase					=				tokenizer.special_tokens_map["""cls_token"""]  # `<s>`
            _lowerCAmelCase					=				tokenizer.special_tokens_map["""sep_token"""]  # `</s>`
      elif args.tokenizer_type == "gpt2":
            _lowerCAmelCase					=				GPTaTokenizer.from_pretrained(args.tokenizer_name    )
            _lowerCAmelCase					=				tokenizer.special_tokens_map["""bos_token"""]  # `<|endoftext|>`
            _lowerCAmelCase					=				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:
            _lowerCAmelCase					=				fp.readlines()

      logger.info("""Start encoding"""    )
      logger.info(f"{len(lowerCAmelCase    )} examples to process."    )

      _lowerCAmelCase					=				[]
      _lowerCAmelCase					=				0
      _lowerCAmelCase					=				1_00_00
      _lowerCAmelCase					=				time.time()
      for text in data:
            _lowerCAmelCase					=				f"{bos} {text.strip()} {sep}"
            _lowerCAmelCase					=				tokenizer.encode(lowerCAmelCase				,      add_special_tokens=lowerCAmelCase    )
            rslt.append(lowerCAmelCase    )

            iter += 1
            if iter % interval == 0:
                  _lowerCAmelCase					=				time.time()
                  logger.info(f"{iter} examples processed. - {(end-start):.2f}s/{interval}expl"    )
                  _lowerCAmelCase					=				time.time()
      logger.info("""Finished binarization"""    )
      logger.info(f"{len(lowerCAmelCase    )} examples processed."    )

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


if __name__ == "__main__":
      main()






