


'''simple docstring'''

import os
from argparse import ArgumentParser, Namespace

from ..data import SingleSentenceClassificationProcessor as Processor
from ..pipelines import TextClassificationPipeline
from ..utils import is_tf_available, is_torch_available, logging
from . import BaseTransformersCLICommand


if not is_tf_available() and not is_torch_available():
     raise RuntimeError("""At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training""")

# TF training parameters
a_  :				Optional[Any]						= False
a_  :				int						= False





def __snake_case					(      UpperCAmelCase_						:						Namespace		):
 return TrainCommand(UpperCAmelCase_		)







class      snake_case    (    lowercase			):





  """simple docstring"""




  @staticmethod
  def   snake_case		(    UpperCamelCase     ):







   """simple docstring"""
   lowerCamelCase_      =  parser.add_parser("train"			,  help="CLI tool to train a model on a task."     )

   train_parser.add_argument(
       "--train_data"			,  type=UpperCamelCase			,  required=UpperCamelCase			,  help="path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences."			,  )
   train_parser.add_argument(
       "--column_label"			,  type=UpperCamelCase			,  default=0			,  help="Column of the dataset csv file with example labels."     )
   train_parser.add_argument(
       "--column_text"			,  type=UpperCamelCase			,  default=1			,  help="Column of the dataset csv file with example texts."     )
   train_parser.add_argument(
       "--column_id"			,  type=UpperCamelCase			,  default=2			,  help="Column of the dataset csv file with example ids."     )
   train_parser.add_argument(
       "--skip_first_row"			,  action="store_true"			,  help="Skip the first row of the csv file (headers)."     )

   train_parser.add_argument("--validation_data"			,  type=UpperCamelCase			,  default=""			,  help="path to validation dataset."     )
   train_parser.add_argument(
       "--validation_split"			,  type=UpperCamelCase			,  default=0.1			,  help="if validation dataset is not provided, fraction of train dataset to use as validation dataset."			,  )

   train_parser.add_argument("--output"			,  type=UpperCamelCase			,  default="./"			,  help="path to saved the trained model."     )

   train_parser.add_argument(
       "--task"			,  type=UpperCamelCase			,  default="text_classification"			,  help="Task to train the model on."     )
   train_parser.add_argument(
       "--model"			,  type=UpperCamelCase			,  default="bert-base-uncased"			,  help="Model's name or path to stored model."     )
   train_parser.add_argument("--train_batch_size"			,  type=UpperCamelCase			,  default=32			,  help="Batch size for training."     )
   train_parser.add_argument("--valid_batch_size"			,  type=UpperCamelCase			,  default=64			,  help="Batch size for validation."     )
   train_parser.add_argument("--learning_rate"			,  type=UpperCamelCase			,  default=3e-5			,  help="Learning rate."     )
   train_parser.add_argument("--adam_epsilon"			,  type=UpperCamelCase			,  default=1e-08			,  help="Epsilon for Adam optimizer."     )
   train_parser.set_defaults(func=UpperCamelCase     )






  def __init__(    self			,  UpperCamelCase     ):







   """simple docstring"""
   lowerCamelCase_      =  logging.get_logger("transformers-cli/training"     )

   lowerCamelCase_      =  "tf" if is_tf_available() else "torch"

   os.makedirs(args.output			,  exist_ok=UpperCamelCase     )
   lowerCamelCase_      =  args.output

   lowerCamelCase_      =  args.column_label
   lowerCamelCase_      =  args.column_text
   lowerCamelCase_      =  args.column_id

   self.logger.info(f'''Loading {args.task} pipeline for {args.model}'''     )
   if args.task == "text_classification":
    lowerCamelCase_      =  TextClassificationPipeline.from_pretrained(args.model     )
   elif args.task == "token_classification":
    raise NotImplementedError
   elif args.task == "question_answering":
    raise NotImplementedError

   self.logger.info(f'''Loading dataset from {args.train_data}'''     )
   lowerCamelCase_      =  Processor.create_from_csv(
       args.train_data			,  column_label=args.column_label			,  column_text=args.column_text			,  column_id=args.column_id			,  skip_first_row=args.skip_first_row			,  )
   lowerCamelCase_      =  None
   if args.validation_data:
    self.logger.info(f'''Loading validation dataset from {args.validation_data}'''     )
    lowerCamelCase_      =  Processor.create_from_csv(
        args.validation_data			,  column_label=args.column_label			,  column_text=args.column_text			,  column_id=args.column_id			,  skip_first_row=args.skip_first_row			,  )

   lowerCamelCase_      =  args.validation_split
   lowerCamelCase_      =  args.train_batch_size
   lowerCamelCase_      =  args.valid_batch_size
   lowerCamelCase_      =  args.learning_rate
   lowerCamelCase_      =  args.adam_epsilon






  def   snake_case		(    self     ):







   """simple docstring"""
   if self.framework == "tf":
    return self.run_tf()
   return self.run_torch()






  def   snake_case		(    self     ):







   """simple docstring"""
   raise NotImplementedError







  def   snake_case		(    self     ):







   """simple docstring"""
   self.pipeline.fit(
       self.train_dataset			,  validation_data=self.valid_dataset			,  validation_split=self.validation_split			,  learning_rate=self.learning_rate			,  adam_epsilon=self.adam_epsilon			,  train_batch_size=self.train_batch_size			,  valid_batch_size=self.valid_batch_size			,  )

   # Save trained pipeline
   self.pipeline.save_pretrained(self.output     )







'''simple docstring'''

import os
import unicodedata
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import SPIECE_UNDERLINE, logging


a_  :				Any						= logging.get_logger(__name__)

a_  :				Optional[Any]						= {"""vocab_file""": """spiece.model"""}

a_  :				Tuple						= {
    """vocab_file""": {
        """TsinghuaAI/CPM-Generate""": """https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model""",
    }
}





class      snake_case    (    lowercase			):





  """simple docstring"""




  def __init__(    self			,  UpperCamelCase			,  UpperCamelCase=False			,  UpperCamelCase=True			,  UpperCamelCase=False			,  UpperCamelCase="<s>"			,  UpperCamelCase="</s>"			,  UpperCamelCase="<unk>"			,  UpperCamelCase="<sep>"			,  UpperCamelCase="<pad>"			,  UpperCamelCase="<cls>"			,  UpperCamelCase="<mask>"			,  UpperCamelCase=["<eop>", "<eod>"]			,  UpperCamelCase = None			,  **UpperCamelCase			,  ):







   """simple docstring"""
   lowerCamelCase_      =  AddedToken(UpperCamelCase			,  lstrip=UpperCamelCase			,  rstrip=UpperCamelCase     ) if isinstance(UpperCamelCase			,  UpperCamelCase     ) else mask_token

   lowerCamelCase_      =  {} if sp_model_kwargs is None else sp_model_kwargs

   super().__init__(
       do_lower_case=UpperCamelCase			,  remove_space=UpperCamelCase			,  keep_accents=UpperCamelCase			,  bos_token=UpperCamelCase			,  eos_token=UpperCamelCase			,  unk_token=UpperCamelCase			,  sep_token=UpperCamelCase			,  pad_token=UpperCamelCase			,  cls_token=UpperCamelCase			,  mask_token=UpperCamelCase			,  additional_special_tokens=UpperCamelCase			,  sp_model_kwargs=self.sp_model_kwargs			,  **UpperCamelCase			,  )

   lowerCamelCase_      =  3

   lowerCamelCase_      =  do_lower_case
   lowerCamelCase_      =  remove_space
   lowerCamelCase_      =  keep_accents
   lowerCamelCase_      =  vocab_file

   lowerCamelCase_      =  spm.SentencePieceProcessor(**self.sp_model_kwargs     )
   self.sp_model.Load(UpperCamelCase     )

   try:
    import jieba
   except ModuleNotFoundError as error:
    raise error.__class__(
        "You need to install jieba to use CpmTokenizer or CpmTokenizerFast. "
        "See https://pypi.org/project/jieba/ for installation."     )
   lowerCamelCase_      =  jieba
   lowerCamelCase_      =  str.maketrans(" \n"			,  "\u2582\u2583"     )






  @property
  # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size
  def   snake_case		(    self     ):







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






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  {self.convert_ids_to_tokens(UpperCamelCase     ): i for i in range(self.vocab_size     )}
   vocab.update(self.added_tokens_encoder     )
   return vocab






  def __getstate__(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  self.__dict__.copy()
   lowerCamelCase_      =  None
   return state






  def __setstate__(    self			,  UpperCamelCase     ):







   """simple docstring"""
   lowerCamelCase_      =  d

   # for backward compatibility
   if not hasattr(self			,  "sp_model_kwargs"     ):
    lowerCamelCase_      =  {}

   lowerCamelCase_      =  spm.SentencePieceProcessor(**self.sp_model_kwargs     )
   self.sp_model.Load(self.vocab_file     )






  def   snake_case		(    self			,  UpperCamelCase     ):







   """simple docstring"""
   if self.remove_space:
    lowerCamelCase_      =  " ".join(inputs.strip().split()     )
   else:
    lowerCamelCase_      =  inputs
   lowerCamelCase_      =  outputs.replace("``"			,  "\""     ).replace("''"			,  "\""     )

   if not self.keep_accents:
    lowerCamelCase_      =  unicodedata.normalize("NFKD"			,  UpperCamelCase     )
    lowerCamelCase_      =  "".join([c for c in outputs if not unicodedata.combining(UpperCamelCase     )]     )
   if self.do_lower_case:
    lowerCamelCase_      =  outputs.lower()

   return outputs






  def   snake_case		(    self			,  UpperCamelCase     ):







   """simple docstring"""
   lowerCamelCase_      =  self.preprocess_text(UpperCamelCase     )
   lowerCamelCase_      =  self.sp_model.encode(UpperCamelCase			,  out_type=UpperCamelCase     )
   lowerCamelCase_      =  []
   for piece in pieces:
    if len(UpperCamelCase     ) > 1 and piece[-1] == str(","     ) and piece[-2].isdigit():
     lowerCamelCase_      =  self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCamelCase			,  ""     )     )
     if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
      if len(cur_pieces[0]     ) == 1:
       lowerCamelCase_      =  cur_pieces[1:]
      else:
       lowerCamelCase_      =  cur_pieces[0][1:]
     cur_pieces.append(piece[-1]     )
     new_pieces.extend(UpperCamelCase     )
    else:
     new_pieces.append(UpperCamelCase     )

   return new_pieces






  def   snake_case		(    self			,  UpperCamelCase     ):







   """simple docstring"""
   return self.sp_model.PieceToId(UpperCamelCase     )






  def   snake_case		(    self			,  UpperCamelCase     ):







   """simple docstring"""
   return self.sp_model.IdToPiece(UpperCamelCase     )






  def   snake_case		(    self			,  UpperCamelCase     ):







   """simple docstring"""
   lowerCamelCase_      =  "".join(UpperCamelCase     ).replace(UpperCamelCase			,  " "     ).strip()
   return out_string






  def   snake_case		(    self			,  UpperCamelCase			,  UpperCamelCase = None     ):







   """simple docstring"""
   lowerCamelCase_      =  [self.sep_token_id]
   lowerCamelCase_      =  [self.cls_token_id]
   if token_ids_a is None:
    return token_ids_a + sep + cls
   return token_ids_a + sep + token_ids_a + sep + cls






  def   snake_case		(    self			,  UpperCamelCase			,  UpperCamelCase = None			,  UpperCamelCase = False     ):







   """simple docstring"""

   if already_has_special_tokens:
    return super().get_special_tokens_mask(
        token_ids_a=UpperCamelCase			,  token_ids_a=UpperCamelCase			,  already_has_special_tokens=UpperCamelCase     )

   if token_ids_a is not None:
    return ([0] * len(UpperCamelCase     )) + [1] + ([0] * len(UpperCamelCase     )) + [1, 1]
   return ([0] * len(UpperCamelCase     )) + [1, 1]






  def   snake_case		(    self			,  UpperCamelCase			,  UpperCamelCase = None     ):







   """simple docstring"""
   lowerCamelCase_      =  [self.sep_token_id]
   lowerCamelCase_      =  [2]

   if token_ids_a is None:
    return len(token_ids_a + sep     ) * [0] + cls_segment_id
   return len(token_ids_a + sep     ) * [0] + len(token_ids_a + sep     ) * [1] + cls_segment_id






  def   snake_case		(    self			,  UpperCamelCase			,  UpperCamelCase = None     ):







   """simple docstring"""
   if not os.path.isdir(UpperCamelCase     ):
    logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''     )
    return
   lowerCamelCase_      =  os.path.join(
       UpperCamelCase			,  (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]     )

   if os.path.abspath(self.vocab_file     ) != os.path.abspath(UpperCamelCase     ) and os.path.isfile(self.vocab_file     ):
    copyfile(self.vocab_file			,  UpperCamelCase     )
   elif not os.path.isfile(self.vocab_file     ):
    with open(UpperCamelCase			,  "wb"     ) as fi:
     lowerCamelCase_      =  self.sp_model.serialized_model_proto()
     fi.write(UpperCamelCase     )

   return (out_vocab_file,)







  def   snake_case		(    self			,  *UpperCamelCase			,  **UpperCamelCase     ):







   """simple docstring"""
   lowerCamelCase_      =  super()._decode(*UpperCamelCase			,  **UpperCamelCase     )
   lowerCamelCase_      =  text.replace(" "			,  ""     ).replace("\u2582"			,  " "     ).replace("\u2583"			,  "\n"     )
   return text



