





import argparse
import logging
import os

import datasets
import tensorflow as tf

from transformers import AutoTokenizer


_lowerCamelCase			       =      logging.getLogger(__name__)




def    __UpperCAmelCase(      ):
       _lowerCamelCase							:     Dict	=		argparse.ArgumentParser(
           description='''Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.'''      )
       parser.add_argument(
           '''--dataset_name''' ,    type=lowercase_ ,    default='''wikitext''' ,    help='''Name of the training. Explore datasets at: hf.co/datasets.''' ,    )
       parser.add_argument(
           '''--dataset_config''' ,    type=lowercase_ ,    default='''wikitext-103-raw-v1''' ,    help='''Configuration name of the dataset.'''      )
       parser.add_argument(
           '''--tokenizer_name_or_path''' ,    type=lowercase_ ,    default='''sayakpaul/unigram-tokenizer-wikitext''' ,    help='''Tokenizer identifier. Can be a local filepath or a Hub identifier.''' ,    )
       parser.add_argument(
           '''--shard_size''' ,    type=lowercase_ ,    default=10_00 ,    help='''Number of entries to go in a single shard.''' ,    )
       parser.add_argument('''--split''' ,    type=lowercase_ ,    default='''train''' ,    choices=['''train''', '''test''', '''validation''']      )
       parser.add_argument(
           '''--limit''' ,    default=lowercase_ ,    type=lowercase_ ,    help='''Limit the number of shards (used for debugging).''' ,    )
       parser.add_argument(
           '''--max_length''' ,    type=lowercase_ ,    default=5_12 ,    help='''Maximum sequence length. For training on TPUs, it helps to have a maximum'''
           ''' sequence length that is a multiple of 8.''' ,    )
       parser.add_argument(
           '''--output_dir''' ,    default='''tf-tpu''' ,    type=lowercase_ ,    help='''Output directory where the TFRecord shards will be saved. If the'''
           ''' path is appended with `gs://` (\'gs://tf-tpu\', for example) then the TFRecord'''
           ''' shards will be directly saved to a Google Cloud Storage bucket.''' ,    )

       _lowerCamelCase							:     Union[str, Any]	=		parser.parse_args()
       return args




def    __UpperCAmelCase(      lowercase_      ):
       def fn(lowercase_      ):
              return tokenizer(examples['''text''']      )

       return fn




def    __UpperCAmelCase(      lowercase_      ):
       _lowerCamelCase							:     Optional[Any]	=		[]
       for i in range(len(tokenized_data['''input_ids''']      )      ):
              _lowerCamelCase							:     Optional[Any]	=		{
                  '''input_ids''': tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data['''input_ids'''][i]      )      ),
                  '''attention_mask''': tf.train.Feature(
                      intaa_list=tf.train.IntaaList(value=tokenized_data['''attention_mask'''][i]      )      ),
              }
              _lowerCamelCase							:     Tuple	=		tf.train.Features(feature=lowercase_      )
              _lowerCamelCase							:     List[str]	=		tf.train.Example(features=lowercase_      )
              _lowerCamelCase							:     Dict	=		example.SerializeToString()
              records.append(lowercase_      )
       return records




def    __UpperCAmelCase(      lowercase_      ):
       _lowerCamelCase							:     Optional[int]	=		datasets.load_dataset(args.dataset_name ,    args.dataset_config ,    split=args.split      )

       if args.limit is not None:
              _lowerCamelCase							:     Optional[Any]	=		min(len(lowercase_      ) ,    args.limit      )
              _lowerCamelCase							:     int	=		dataset.select(range(lowercase_      )      )
              print(F"""Limiting the dataset to {args.limit} entries."""      )

       _lowerCamelCase							:     str	=		AutoTokenizer.from_pretrained(args.tokenizer_name_or_path      )

       # Handle output directory creation.
       # For serializing into a Google Cloud Storage Bucket, one needs to first
       # create a bucket.
       if "gs" not in args.output_dir:
              if not os.path.exists(args.output_dir      ):
                     os.makedirs(args.output_dir      )
              _lowerCamelCase							:     Optional[Any]	=		os.path.join(args.output_dir ,    args.split      )
              if not os.path.exists(lowercase_      ):
                     os.makedirs(lowercase_      )
       else:
              _lowerCamelCase							:     Optional[Any]	=		os.path.join(args.output_dir ,    args.split      )

       # Tokenize the whole dataset at once.
       _lowerCamelCase							:     Any	=		tokenize_function(lowercase_      )
       _lowerCamelCase							:     Dict	=		dataset.map(lowercase_ ,    batched=lowercase_ ,    num_proc=4 ,    remove_columns=['''text''']      )

       # We need to concatenate all our texts together, and then split the result
       # into chunks of a fixed size, which we will call block_size. To do this, we
       # will use the map method again, with the option batched=True. When we use batched=True,
       # the function we pass to map() will be passed multiple inputs at once, allowing us
       # to group them into more or fewer examples than we had in the input.
       # This allows us to create our new fixed-length samples. The advantage of this
       # method is that we don't lose a whole lot of content from the dataset compared to the
       # case where we simply tokenize with a pre-defined max_length.

       def group_texts(lowercase_      ):
              # Concatenate all texts.
              _lowerCamelCase							:     Union[str, Any]	=		{k: sum(examples[k] ,    []      ) for k in examples.keys()}
              _lowerCamelCase							:     Any	=		len(concatenated_examples[list(examples.keys()      )[0]]      )
              # We drop the small remainder, though you could add padding instead if the model supports it
              # In this, as in all things, we advise you to follow your heart 🫀
              _lowerCamelCase							:     List[str]	=		(total_length // args.max_length) * args.max_length
              # Split by chunks of max_len.
              _lowerCamelCase							:     int	=		{
                  k: [t[i : i + args.max_length] for i in range(0 ,    lowercase_ ,    args.max_length      )]
                  for k, t in concatenated_examples.items()
              }
              return result

       _lowerCamelCase							:     int	=		dataset_tokenized.map(lowercase_ ,    batched=lowercase_ ,    batch_size=10_00 ,    num_proc=4      )

       _lowerCamelCase							:     List[Any]	=		0
       _lowerCamelCase							:     Optional[int]	=		0
       for shard in range(0 ,    len(lowercase_      ) ,    args.shard_size      ):
              _lowerCamelCase							:     List[str]	=		grouped_dataset[shard : shard + args.shard_size]
              _lowerCamelCase							:     Optional[Any]	=		len(dataset_snapshot['''input_ids''']      )
              _lowerCamelCase							:     str	=		os.path.join(lowercase_ ,    F"""dataset-{shard_count}-{records_containing}.tfrecord"""      )
              _lowerCamelCase							:     Union[str, Any]	=		get_serialized_examples(lowercase_      )

              with tf.io.TFRecordWriter(lowercase_      ) as out_file:
                     for i in range(len(lowercase_      )      ):
                            _lowerCamelCase							:     Optional[Any]	=		serialized_examples[i]
                            out_file.write(lowercase_      )
                     print('''Wrote file {} containing {} records'''.format(lowercase_ ,    lowercase_      )      )

              shard_count += 1
              total_records += records_containing

       with open(F"""split-{args.split}-records-count.txt""" ,    '''w'''      ) as f:
              print(F"""Total {args.split} records: {total_records}""" ,    file=lowercase_      )


if __name__ == "__main__":
       _lowerCamelCase			       =      parse_args()
       main(args)








import os
import time
import warnings
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures


_lowerCamelCase			       =      logging.get_logger(__name__)







@dataclass
class 			__A       :




      """simple docstring"""







      UpperCAmelCase__						=      field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(glue_processors.keys()  )}  )
      UpperCAmelCase__						=      field(
          metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""}  )
      UpperCAmelCase__						=      field(
          default=128 ,metadata={
              """help""": (
                  """The maximum total input sequence length after tokenization. Sequences longer """
                  """than this will be truncated, sequences shorter will be padded."""
              )
          } ,)
      UpperCAmelCase__						=      field(
          default=lowerCamelCase__ ,metadata={"""help""": """Overwrite the cached training and evaluation sets"""}  )


      def 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     Dict	=		self.task_name.lower()







class 			__A       (      lowerCamelCase__  ):




      """simple docstring"""







      UpperCAmelCase__						=      """train"""
      UpperCAmelCase__						=      """dev"""
      UpperCAmelCase__						=      """test"""







class 			__A       (      lowerCamelCase__  ):




      """simple docstring"""







      UpperCAmelCase__						=      42
      UpperCAmelCase__						=      42
      UpperCAmelCase__						=      42


      def __init__(		self      ,							a__      ,							a__      ,							a__ = None      ,							a__ = Split.train      ,							a__ = None      ,							):



             """simple docstring"""





             warnings.warn(
                 '''This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets '''
                 '''library. You can have a look at this example script for pointers: '''
                 '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py'''      ,							a__      ,							)
             _lowerCamelCase							:     Optional[Any]	=		args
             _lowerCamelCase							:     Tuple	=		glue_processors[args.task_name]()
             _lowerCamelCase							:     Any	=		glue_output_modes[args.task_name]
             if isinstance(a__      ,							a__):
                    try:
                           _lowerCamelCase							:     List[Any]	=		Split[mode]
                    except KeyError:
                           raise KeyError('''mode is not a valid split name''')
        # Load data features from cache or dataset file
             _lowerCamelCase							:     Tuple	=		os.path.join(
                 cache_dir if cache_dir is not None else args.data_dir      ,							F"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}"""      ,							)
             _lowerCamelCase							:     int	=		self.processor.get_labels()
             if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
                 "RobertaTokenizer",
                 "RobertaTokenizerFast",
                 "XLMRobertaTokenizer",
                 "BartTokenizer",
                 "BartTokenizerFast",
             ):
                    # HACK(label indices are swapped in RoBERTa pretrained model)
                    _lowerCamelCase,  _lowerCamelCase							:     Union[str, Any]	=		label_list[2], label_list[1]
             _lowerCamelCase							:     str	=		label_list

             # Make sure only the first process in distributed training processes the dataset,
             # and the others will use the cache.
             _lowerCamelCase							:     Any	=		cached_features_file + '''.lock'''
             with FileLock(a__):
                    if os.path.exists(a__) and not args.overwrite_cache:
                           _lowerCamelCase							:     Any	=		time.time()
                           _lowerCamelCase							:     Optional[Any]	=		torch.load(a__)
                           logger.info(
                               F"""Loading features from cached file {cached_features_file} [took %.3f s]"""      ,							time.time() - start)
                    else:
                           logger.info(F"""Creating features from dataset file at {args.data_dir}""")

                           if mode == Split.dev:
                                  _lowerCamelCase							:     List[str]	=		self.processor.get_dev_examples(args.data_dir)
                           elif mode == Split.test:
                                  _lowerCamelCase							:     str	=		self.processor.get_test_examples(args.data_dir)
                           else:
                                  _lowerCamelCase							:     List[Any]	=		self.processor.get_train_examples(args.data_dir)
                           if limit_length is not None:
                                  _lowerCamelCase							:     List[Any]	=		examples[:limit_length]
                           _lowerCamelCase							:     List[str]	=		glue_convert_examples_to_features(
                               a__      ,							a__      ,							max_length=args.max_seq_length      ,							label_list=a__      ,							output_mode=self.output_mode      ,							)
                           _lowerCamelCase							:     int	=		time.time()
                           torch.save(self.features      ,							a__)
                           # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
                           logger.info(
                               F"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]""")


      def __len__(		self):



             """simple docstring"""





             return len(self.features)


      def __getitem__(		self      ,							a__):



             """simple docstring"""





             return self.features[i]



      def 				__snake_case			(		self):



             """simple docstring"""





             return self.label_list

