




import logging
import math
import os
from dataclasses import dataclass, field
from glob import glob
from typing import Optional

from torch.utils.data import ConcatDataset

import transformers
from transformers import (
    CONFIG_MAPPING,
    MODEL_WITH_LM_HEAD_MAPPING,
    AutoConfig,
    AutoModelWithLMHead,
    AutoTokenizer,
    DataCollatorForLanguageModeling,
    DataCollatorForPermutationLanguageModeling,
    DataCollatorForWholeWordMask,
    HfArgumentParser,
    LineByLineTextDataset,
    LineByLineWithRefDataset,
    PreTrainedTokenizer,
    TextDataset,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


_lowerCAmelCase  :      Optional[Any]						=      logging.getLogger(__name__)


_lowerCAmelCase  :      List[str]						=      list(MODEL_WITH_LM_HEAD_MAPPING.keys())
_lowerCAmelCase  :      int						=      tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
@dataclass
class 	_UpperCamelCase					:
      UpperCAmelCase_						=						field(
          default=UpperCamelCase__		,				metadata={
              """help""": (
                  """The model checkpoint for weights initialization. Leave None if you want to train a model from"""
                  """ scratch."""
              )
          }		,				)
      UpperCAmelCase_						=						field(
          default=UpperCamelCase__		,				metadata={"""help""": """If training from scratch, pass a model type from the list: """ + """, """.join(UpperCamelCase__						)}		,				)
      UpperCAmelCase_						=						field(
          default=UpperCamelCase__		,				metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}						)
      UpperCAmelCase_						=						field(
          default=UpperCamelCase__		,				metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}						)
      UpperCAmelCase_						=						field(
          default=UpperCamelCase__		,				metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}		,				)



@dataclass
class 	_UpperCamelCase					:
      UpperCAmelCase_						=						field(
          default=UpperCamelCase__		,				metadata={"""help""": """The input training data file (a text file)."""}						)
      UpperCAmelCase_						=						field(
          default=UpperCamelCase__		,				metadata={
              """help""": (
                  """The input training data files (multiple files in glob format). """
                  """Very often splitting large files to smaller files can prevent tokenizer going out of memory"""
              )
          }		,				)
      UpperCAmelCase_						=						field(
          default=UpperCamelCase__		,				metadata={"""help""": """An optional input evaluation data file to evaluate the perplexity on (a text file)."""}		,				)
      UpperCAmelCase_						=						field(
          default=UpperCamelCase__		,				metadata={"""help""": """An optional input train ref data file for whole word mask in Chinese."""}		,				)
      UpperCAmelCase_						=						field(
          default=UpperCamelCase__		,				metadata={"""help""": """An optional input eval ref data file for whole word mask in Chinese."""}		,				)
      UpperCAmelCase_						=						field(
          default=UpperCamelCase__		,				metadata={"""help""": """Whether distinct lines of text in the dataset are to be handled as distinct sequences."""}		,				)

      UpperCAmelCase_						=						field(
          default=UpperCamelCase__		,				metadata={"""help""": """Train with masked-language modeling loss instead of language modeling."""}						)
      UpperCAmelCase_						=						field(default=UpperCamelCase__		,				metadata={"""help""": """Whether ot not to use whole word mask."""}						)
      UpperCAmelCase_						=						field(
          default=0.15		,				metadata={"""help""": """Ratio of tokens to mask for masked language modeling loss"""}						)
      UpperCAmelCase_						=						field(
          default=1 / 6		,				metadata={
              """help""": (
                  """Ratio of length of a span of masked tokens to surrounding context length for permutation language"""
                  """ modeling."""
              )
          }		,				)
      UpperCAmelCase_						=						field(
          default=5		,				metadata={"""help""": """Maximum length of a span of masked tokens for permutation language modeling."""}						)

      UpperCAmelCase_						=						field(
          default=-1		,				metadata={
              """help""": (
                  """Optional input sequence length after tokenization."""
                  """The training dataset will be truncated in block of this size for training."""
                  """Default to the model max input length for single sentence inputs (take into account special tokens)."""
              )
          }		,				)
      UpperCAmelCase_						=						field(
          default=UpperCamelCase__		,				metadata={"""help""": """Overwrite the cached training and evaluation sets"""}						)



def   lowerCAmelCase						(						_lowerCAmelCase							:      Dict  ,							_lowerCAmelCase							:      str  ,							_lowerCAmelCase							:      Optional[int] = False  ,							_lowerCAmelCase							:      int = None  ,							):




 """simple docstring"""







 def _dataset(_lowerCAmelCase							:      Dict  ,							_lowerCAmelCase							:      Tuple=None		):
  if args.line_by_line:
   if ref_path is not None:
    if not args.whole_word_mask or not args.mlm:
     raise ValueError("You need to set world whole masking and mlm to True for Chinese Whole Word Mask"		)
    return LineByLineWithRefDataset(
        tokenizer=_lowerCAmelCase  ,							file_path=_lowerCAmelCase  ,							block_size=args.block_size  ,							ref_path=_lowerCAmelCase  ,							)

   return LineByLineTextDataset(tokenizer=_lowerCAmelCase  ,							file_path=_lowerCAmelCase  ,							block_size=args.block_size		)
  else:
   return TextDataset(
       tokenizer=_lowerCAmelCase  ,							file_path=_lowerCAmelCase  ,							block_size=args.block_size  ,							overwrite_cache=args.overwrite_cache  ,							cache_dir=_lowerCAmelCase  ,							)

 if evaluate:
  return _dataset(args.eval_data_file  ,							args.eval_ref_file		)
 elif args.train_data_files:
  return ConcatDataset([_dataset(_lowerCAmelCase		) for f in glob(args.train_data_files		)]		)
 else:
  return _dataset(args.train_data_file  ,							args.train_ref_file		)



def   lowerCAmelCase						(						):




 """simple docstring"""







 UpperCAmelCase__							       =  HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)		)
 UpperCAmelCase__       ,       UpperCAmelCase__       ,       UpperCAmelCase__							       =  parser.parse_args_into_dataclasses()

 if data_args.eval_data_file is None and training_args.do_eval:
  raise ValueError(
      "Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file "
      "or remove the --do_eval argument."		)
 if (
     os.path.exists(training_args.output_dir		)
     and os.listdir(training_args.output_dir		)
     and training_args.do_train
     and not training_args.overwrite_output_dir
 ):
  raise ValueError(
      F'''Output directory ({training_args.output_dir}) already exists and is not empty. Use'''
      " --overwrite_output_dir to overcome."		)

 # Setup logging
 logging.basicConfig(
     format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"  ,							datefmt="%m/%d/%Y %H:%M:%S"  ,							level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN  ,							)
 logger.warning(
     "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s"  ,							training_args.local_rank  ,							training_args.device  ,							training_args.n_gpu  ,							bool(training_args.local_rank != -1		)  ,							training_args.fpaa  ,							)
 # Set the verbosity to info of the Transformers logger (on main process only):
 if is_main_process(training_args.local_rank		):
  transformers.utils.logging.set_verbosity_info()
  transformers.utils.logging.enable_default_handler()
  transformers.utils.logging.enable_explicit_format()
 logger.info("Training/evaluation parameters %s"  ,							_lowerCAmelCase		)

 # Set seed
 set_seed(training_args.seed		)

 # Load pretrained model and tokenizer
 #
 # Distributed training:
 # The .from_pretrained methods guarantee that only one local process can concurrently
 # download model & vocab.

 if model_args.config_name:
  UpperCAmelCase__							       =  AutoConfig.from_pretrained(model_args.config_name  ,							cache_dir=model_args.cache_dir		)
 elif model_args.model_name_or_path:
  UpperCAmelCase__							       =  AutoConfig.from_pretrained(model_args.model_name_or_path  ,							cache_dir=model_args.cache_dir		)
 else:
  UpperCAmelCase__							       =  CONFIG_MAPPING[model_args.model_type]()
  logger.warning("You are instantiating a new config instance from scratch."		)

 if model_args.tokenizer_name:
  UpperCAmelCase__							       =  AutoTokenizer.from_pretrained(model_args.tokenizer_name  ,							cache_dir=model_args.cache_dir		)
 elif model_args.model_name_or_path:
  UpperCAmelCase__							       =  AutoTokenizer.from_pretrained(model_args.model_name_or_path  ,							cache_dir=model_args.cache_dir		)
 else:
  raise ValueError(
      "You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another"
      " script, save it,and load it from here, using --tokenizer_name"		)

 if model_args.model_name_or_path:
  UpperCAmelCase__							       =  AutoModelWithLMHead.from_pretrained(
      model_args.model_name_or_path  ,							from_tf=bool(".ckpt" in model_args.model_name_or_path		)  ,							config=_lowerCAmelCase  ,							cache_dir=model_args.cache_dir  ,							)
 else:
  logger.info("Training new model from scratch"		)
  UpperCAmelCase__							       =  AutoModelWithLMHead.from_config(_lowerCAmelCase		)

 model.resize_token_embeddings(len(_lowerCAmelCase		)		)

 if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm:
  raise ValueError(
      "BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the"
      "--mlm flag (masked language modeling)."		)

 if data_args.block_size <= 0:
  UpperCAmelCase__							       =  tokenizer.max_len
  # Our input block size will be the max possible for the model
 else:
  UpperCAmelCase__							       =  min(data_args.block_size  ,							tokenizer.max_len		)

 # Get datasets

 UpperCAmelCase__							       =  (
     get_dataset(_lowerCAmelCase  ,							tokenizer=_lowerCAmelCase  ,							cache_dir=model_args.cache_dir		) if training_args.do_train else None
 )
 UpperCAmelCase__							       =  (
     get_dataset(_lowerCAmelCase  ,							tokenizer=_lowerCAmelCase  ,							evaluate=_lowerCAmelCase  ,							cache_dir=model_args.cache_dir		)
     if training_args.do_eval
     else None
 )
 if config.model_type == "xlnet":
  UpperCAmelCase__							       =  DataCollatorForPermutationLanguageModeling(
      tokenizer=_lowerCAmelCase  ,							plm_probability=data_args.plm_probability  ,							max_span_length=data_args.max_span_length  ,							)
 else:
  if data_args.mlm and data_args.whole_word_mask:
   UpperCAmelCase__							       =  DataCollatorForWholeWordMask(
       tokenizer=_lowerCAmelCase  ,							mlm_probability=data_args.mlm_probability		)
  else:
   UpperCAmelCase__							       =  DataCollatorForLanguageModeling(
       tokenizer=_lowerCAmelCase  ,							mlm=data_args.mlm  ,							mlm_probability=data_args.mlm_probability		)

    # Initialize our Trainer
 UpperCAmelCase__							       =  Trainer(
     model=_lowerCAmelCase  ,							args=_lowerCAmelCase  ,							data_collator=_lowerCAmelCase  ,							train_dataset=_lowerCAmelCase  ,							eval_dataset=_lowerCAmelCase  ,							prediction_loss_only=_lowerCAmelCase  ,							)

 # Training
 if training_args.do_train:
  UpperCAmelCase__							       =  (
      model_args.model_name_or_path
      if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path		)
      else None
  )
  trainer.train(model_path=_lowerCAmelCase		)
  trainer.save_model()
  # For convenience, we also re-save the tokenizer to the same directory,
  # so that you can share your model easily on huggingface.co/models =)
  if trainer.is_world_master():
   tokenizer.save_pretrained(training_args.output_dir		)

    # Evaluation
 UpperCAmelCase__							       =  {}
 if training_args.do_eval:
  logger.info("*** Evaluate ***"		)

  UpperCAmelCase__							       =  trainer.evaluate()

  UpperCAmelCase__							       =  math.exp(eval_output["eval_loss"]		)
  UpperCAmelCase__							       =  {"perplexity": perplexity}

  UpperCAmelCase__							       =  os.path.join(training_args.output_dir  ,							"eval_results_lm.txt"		)
  if trainer.is_world_master():
   with open(_lowerCAmelCase  ,							"w"		) as writer:
    logger.info("***** Eval results *****"		)
    for key in sorted(result.keys()		):
     logger.info("  %s = %s"  ,							_lowerCAmelCase  ,							str(result[key]		)		)
     writer.write("%s = %s\n" % (key, str(result[key]		))		)

  results.update(_lowerCAmelCase		)

 return results



def   lowerCAmelCase						(						_lowerCAmelCase							:      List[str]		):




 """simple docstring"""







 main()


if __name__ == "__main__":
  main()









import os
import re
import shutil
from argparse import ArgumentParser, Namespace

from datasets.commands import BaseDatasetsCLICommand
from datasets.utils.logging import get_logger


lowerCAmelCase       =							'<<<<<<< This should probably be modified because it mentions: '

lowerCAmelCase       =							'=======\n>>>>>>>\n'

lowerCAmelCase       =							[
    'TextEncoderConfig',
    'ByteTextEncoder',
    'SubwordTextEncoder',
    'encoder_config',
    'maybe_build_from_corpus',
    'manual_dir',
]

lowerCAmelCase       =							[
    # (pattern, replacement)
    # Order is important here for some replacements
    (R'tfds\.core', R'datasets'),
    (R'tf\.io\.gfile\.GFile', R'open'),
    (R'tf\.([\w\d]+)', R'datasets.Value(\'\1\')'),
    (R'tfds\.features\.Text\(\)', R'datasets.Value(\'string\')'),
    (R'tfds\.features\.Text\(', R'datasets.Value(\'string\'),'),
    (R'features\s*=\s*tfds.features.FeaturesDict\(', R'features=datasets.Features('),
    (R'tfds\.features\.FeaturesDict\(', R'dict('),
    (R'The TensorFlow Datasets Authors', R'The TensorFlow Datasets Authors and the HuggingFace Datasets Authors'),
    (R'tfds\.', R'datasets.'),
    (R'dl_manager\.manual_dir', R'self.config.data_dir'),
    (R'self\.builder_config', R'self.config'),
]
def 			_a (      SCREAMING_SNAKE_CASE     ):


		"""simple docstring"""




		return ConvertCommand(args.tfds_path						,				args.datasets_directory     )


class        _a							(			UpperCamelCase__			):

							@staticmethod
							def       lowerCamelCase_ (							UpperCamelCase_:	ArgumentParser							)			->   int:





									"""simple docstring"""







									lowercase__            =      parser.add_parser(
									    '''convert'''    ,						help='''Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.'''    ,						)
									train_parser.add_argument(
									    '''--tfds_path'''    ,						type=UpperCamelCase_    ,						required=UpperCamelCase_    ,						help='''Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.'''    ,						)
									train_parser.add_argument(
									    '''--datasets_directory'''    ,						type=UpperCamelCase_    ,						required=UpperCamelCase_    ,						help='''Path to the HuggingFace Datasets folder.'''							)
									train_parser.set_defaults(func=UpperCamelCase_							)

							def __init__(							self:	int    ,						UpperCamelCase_:	str    ,						UpperCamelCase_:	str    ,						*UpperCamelCase_:	Optional[int]							)			->   Union[str, Any]:





									"""simple docstring"""







									lowercase__            =      get_logger('''datasets-cli/converting'''							)

									lowercase__            =      tfds_path
									lowercase__            =      datasets_directory


							def       lowerCamelCase_ (							self:	int							)			->   Optional[int]:





									"""simple docstring"""







									if os.path.isdir(self._tfds_path							):
											lowercase__            =      os.path.abspath(self._tfds_path							)
									elif os.path.isfile(self._tfds_path							):
											lowercase__            =      os.path.dirname(self._tfds_path							)
									else:
											raise ValueError('''--tfds_path is neither a directory nor a file. Please check path.'''							)

									lowercase__            =      os.path.abspath(self._datasets_directory							)

									self._logger.info(f'Converting datasets from {abs_tfds_path} to {abs_datasets_path}'							)

									lowercase__            =      []
									lowercase__            =      []
									lowercase__            =      {}

									if os.path.isdir(self._tfds_path							):
											lowercase__            =      os.listdir(UpperCamelCase_							)
									else:
											lowercase__            =      [os.path.basename(self._tfds_path							)]

									for f_name in file_names:
											self._logger.info(f'Looking at file {f_name}'							)
											lowercase__            =      os.path.join(UpperCamelCase_    ,						UpperCamelCase_							)
											lowercase__            =      os.path.join(UpperCamelCase_    ,						UpperCamelCase_							)

											if not os.path.isfile(UpperCamelCase_							) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name:
													self._logger.info('''Skipping file'''							)
													continue

											with open(UpperCamelCase_    ,						encoding='''utf-8'''							) as f:
													lowercase__            =      f.readlines()

											lowercase__            =      []
											lowercase__            =      False
											lowercase__            =      False
											lowercase__            =      []
											for line in lines:
													lowercase__            =      line

													# Convert imports
													if "import tensorflow.compat.v2 as tf" in out_line:
															continue
													elif "@tfds.core" in out_line:
															continue
													elif "builder=self" in out_line:
															continue
													elif "import tensorflow_datasets.public_api as tfds" in out_line:
															lowercase__            =      '''import datasets\n'''
													elif "import tensorflow" in out_line:
															# order is important here
															lowercase__            =      ''''''
															continue
													elif "from absl import logging" in out_line:
															lowercase__            =      '''from datasets import logging\n'''
													elif "getLogger" in out_line:
															lowercase__            =      out_line.replace('''getLogger'''    ,						'''get_logger'''							)
													elif any(expression in out_line for expression in TO_HIGHLIGHT							):
															lowercase__            =      True
															lowercase__            =      list(filter(lambda UpperCamelCase_							: e in out_line    ,						UpperCamelCase_							)							)
															out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(UpperCamelCase_							) + '''\n'''							)
															out_lines.append(UpperCamelCase_							)
															out_lines.append(UpperCamelCase_							)
															continue
													else:
															for pattern, replacement in TO_CONVERT:
																	lowercase__            =      re.sub(UpperCamelCase_    ,						UpperCamelCase_    ,						UpperCamelCase_							)

                # Take care of saving utilities (to later move them together with main script)
													if "tensorflow_datasets" in out_line:
															lowercase__            =      re.match(r'''from\stensorflow_datasets.*import\s([^\.\r\n]+)'''    ,						UpperCamelCase_							)
															tfds_imports.extend(imp.strip() for imp in match.group(1							).split(''','''							)							)
															lowercase__            =      '''from . import ''' + match.group(1							)

													# Check we have not forget anything
													if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line:
															raise ValueError(f'Error converting {out_line.strip()}'							)

													if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line:
															lowercase__            =      True
													out_lines.append(UpperCamelCase_							)

											if is_builder or "wmt" in f_name:
													# We create a new directory for each dataset
													lowercase__            =      f_name.replace('''.py'''    ,						''''''							)
													lowercase__            =      os.path.join(UpperCamelCase_    ,						UpperCamelCase_							)
													lowercase__            =      os.path.join(UpperCamelCase_    ,						UpperCamelCase_							)
													os.makedirs(UpperCamelCase_    ,						exist_ok=UpperCamelCase_							)
													self._logger.info(f'Adding directory {output_dir}'							)
													imports_to_builder_map.update({imp: output_dir for imp in tfds_imports}							)
											else:
													# Utilities will be moved at the end
													utils_files.append(UpperCamelCase_							)

											if needs_manual_update:
													with_manual_update.append(UpperCamelCase_							)

											with open(UpperCamelCase_    ,						'''w'''    ,						encoding='''utf-8'''							) as f:
													f.writelines(UpperCamelCase_							)
											self._logger.info(f'Converted in {output_file}'							)

									for utils_file in utils_files:
											try:
													lowercase__            =      os.path.basename(UpperCamelCase_							)
													lowercase__            =      imports_to_builder_map[f_name.replace('''.py'''    ,						''''''							)]
													self._logger.info(f'Moving {dest_folder} to {utils_file}'							)
													shutil.copy(UpperCamelCase_    ,						UpperCamelCase_							)
											except KeyError:
													self._logger.error(f'Cannot find destination folder for {utils_file}. Please copy manually.'							)

									if with_manual_update:
											for file_path in with_manual_update:
													self._logger.warning(
													    f'You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.'							)


