



'''simple docstring'''






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: Union[str, Any]							=						logging.getLogger(__name__)


lowerCAmelCase: Optional[Any]							=						list(MODEL_WITH_LM_HEAD_MAPPING.keys())
lowerCAmelCase: Optional[int]							=						tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)

@dataclass
class 							a__:
    lowercase__			=   field(
        default=lowerCamelCase__		,			metadata={
            """help""": (
                """The model checkpoint for weights initialization. Leave None if you want to train a model from"""
                """ scratch."""
            )
        }		,			)
    lowercase__			=   field(
        default=lowerCamelCase__		,			metadata={"""help""": """If training from scratch, pass a model type from the list: """ + """, """.join(lowerCamelCase__     )}		,			)
    lowercase__			=   field(
        default=lowerCamelCase__		,			metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}     )
    lowercase__			=   field(
        default=lowerCamelCase__		,			metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}     )
    lowercase__			=   field(
        default=lowerCamelCase__		,			metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}		,			)

@dataclass
class 							a__:
    lowercase__			=   field(
        default=lowerCamelCase__		,			metadata={"""help""": """The input training data file (a text file)."""}     )
    lowercase__			=   field(
        default=lowerCamelCase__		,			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"""
            )
        }		,			)
    lowercase__			=   field(
        default=lowerCamelCase__		,			metadata={"""help""": """An optional input evaluation data file to evaluate the perplexity on (a text file)."""}		,			)
    lowercase__			=   field(
        default=lowerCamelCase__		,			metadata={"""help""": """An optional input train ref data file for whole word mask in Chinese."""}		,			)
    lowercase__			=   field(
        default=lowerCamelCase__		,			metadata={"""help""": """An optional input eval ref data file for whole word mask in Chinese."""}		,			)
    lowercase__			=   field(
        default=lowerCamelCase__		,			metadata={"""help""": """Whether distinct lines of text in the dataset are to be handled as distinct sequences."""}		,			)

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

    lowercase__			=   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)."""
            )
        }		,			)
    lowercase__			=   field(
        default=lowerCamelCase__		,			metadata={"""help""": """Overwrite the cached training and evaluation sets"""}     )
def 				lowerCamelCase__	(						_A			,      _A			,      _A = False			,      _A = None			,      ):
  def _dataset(_A			,      _A=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=_A			,      file_path=_A			,      block_size=args.block_size			,      ref_path=_A			,      )

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

  if evaluate:
    return _dataset(args.eval_data_file			,      args.eval_ref_file    )
  elif args.train_data_files:
    return ConcatDataset([_dataset(_A    ) for f in glob(args.train_data_files    )]    )
  else:
    return _dataset(args.train_data_file			,      args.train_ref_file    )
def 				lowerCamelCase__	(						):
  # See all possible arguments in src/transformers/training_args.py
  # or by passing the --help flag to this script.
  # We now keep distinct sets of args, for a cleaner separation of concerns.

  a						: Tuple					       =					HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)    )
  a       ,     a       ,     a						: Tuple					       =					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'			,      _A    )

  # 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:
    a						: Optional[Any]					       =					AutoConfig.from_pretrained(model_args.config_name			,      cache_dir=model_args.cache_dir    )
  elif model_args.model_name_or_path:
    a						: List[Any]					       =					AutoConfig.from_pretrained(model_args.model_name_or_path			,      cache_dir=model_args.cache_dir    )
  else:
    a						: Optional[int]					       =					CONFIG_MAPPING[model_args.model_type]()
    logger.warning('You are instantiating a new config instance from scratch.'    )

  if model_args.tokenizer_name:
    a						: List[str]					       =					AutoTokenizer.from_pretrained(model_args.tokenizer_name			,      cache_dir=model_args.cache_dir    )
  elif model_args.model_name_or_path:
    a						: Optional[int]					       =					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:
    a						: List[Any]					       =					AutoModelWithLMHead.from_pretrained(
        model_args.model_name_or_path			,      from_tf=bool('.ckpt' in model_args.model_name_or_path    )			,      config=_A			,      cache_dir=model_args.cache_dir			,      )
  else:
    logger.info('Training new model from scratch'    )
    a						: List[str]					       =					AutoModelWithLMHead.from_config(_A    )

  model.resize_token_embeddings(len(_A    )    )

  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:
    a						: Optional[Any]					       =					tokenizer.max_len
    # Our input block size will be the max possible for the model
  else:
    a						: Any					       =					min(data_args.block_size			,      tokenizer.max_len    )

  # Get datasets

  a						: Union[str, Any]					       =					(
      get_dataset(_A			,      tokenizer=_A			,      cache_dir=model_args.cache_dir    ) if training_args.do_train else None
  )
  a						: str					       =					(
      get_dataset(_A			,      tokenizer=_A			,      evaluate=_A			,      cache_dir=model_args.cache_dir    )
      if training_args.do_eval
      else None
  )
  if config.model_type == "xlnet":
    a						: int					       =					DataCollatorForPermutationLanguageModeling(
        tokenizer=_A			,      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:
      a						: int					       =					DataCollatorForWholeWordMask(
          tokenizer=_A			,      mlm_probability=data_args.mlm_probability    )
    else:
      a						: str					       =					DataCollatorForLanguageModeling(
          tokenizer=_A			,      mlm=data_args.mlm			,      mlm_probability=data_args.mlm_probability    )

    # Initialize our Trainer
  a						: Optional[Any]					       =					Trainer(
      model=_A			,      args=_A			,      data_collator=_A			,      train_dataset=_A			,      eval_dataset=_A			,      prediction_loss_only=_A			,      )

  # Training
  if training_args.do_train:
    a						: Optional[int]					       =					(
        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=_A    )
    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
  a						: Any					       =					{}
  if training_args.do_eval:
    logger.info('*** Evaluate ***'    )

    a						: List[str]					       =					trainer.evaluate()

    a						: Any					       =					math.exp(eval_output['eval_loss']    )
    a						: Any					       =					{'perplexity': perplexity}

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

    results.update(_A    )

  return results
def 				lowerCamelCase__	(						_A    ):
  # For xla_spawn (TPUs)
  main()


if __name__ == "__main__":
     main()




'''simple docstring'''






import os
import pickle
import unittest

from transformers import AutoTokenizer
from transformers.models.bert.tokenization_bert import BertTokenizer
from transformers.models.bert_japanese.tokenization_bert_japanese import (
    VOCAB_FILES_NAMES,
    BertJapaneseTokenizer,
    CharacterTokenizer,
    JumanppTokenizer,
    MecabTokenizer,
    SudachiTokenizer,
    WordpieceTokenizer,
)
from transformers.testing_utils import custom_tokenizers, require_jumanpp, require_sudachi

from ...test_tokenization_common import TokenizerTesterMixin

@custom_tokenizers
class 							a__( lowerCamelCase__		,			unittest.TestCase     ):
    lowercase__			=   BertJapaneseTokenizer
    lowercase__			=   False
    lowercase__			=   True







    def       lowercase_	(				self			:  int     ):
      super().setUp()

      a						: List[Any]					       =					[
          '[UNK]',
          '[CLS]',
          '[SEP]',
          'こんにちは',
          'こん',
          'にちは',
          'ばんは',
          '##こん',
          '##にちは',
          '##ばんは',
          '世界',
          '##世界',
          '、',
          '##、',
          '。',
          '##。',
      ]

      a						: Dict					       =					os.path.join(self.tmpdirname						,      VOCAB_FILES_NAMES['vocab_file']     )
      with open(self.vocab_file						,      'w'						,      encoding='utf-8'     ) as vocab_writer:
        vocab_writer.write(''.join([x + '\n' for x in vocab_tokens]     )     )







    def       lowercase_	(				self			:  Any						,      __snake_case			:  str     ):
      a						: Union[str, Any]					       =					'こんにちは、世界。 \nこんばんは、世界。'
      a						: List[Any]					       =					'こんにちは 、 世界 。 こんばんは 、 世界 。'
      return input_text, output_text







    def       lowercase_	(				self			:  Optional[Any]						,      __snake_case			:  Optional[Any]     ):
      a       ,     a						: List[str]					       =					self.get_input_output_texts(__snake_case     )
      a						: Optional[int]					       =					tokenizer.encode(__snake_case						,      add_special_tokens=__snake_case     )
      a						: str					       =					tokenizer.decode(__snake_case						,      clean_up_tokenization_spaces=__snake_case     )
      return text, ids







    def       lowercase_	(				self			:  Optional[Any]     ):
      pass  # TODO add if relevant







    def       lowercase_	(				self			:  List[Any]     ):
      pass  # TODO add if relevant







    def       lowercase_	(				self			:  Dict     ):
      pass  # TODO add if relevant







    def       lowercase_	(				self			:  List[Any]     ):
      a						: Optional[int]					       =					self.tokenizer_class(self.vocab_file     )

      a						: Optional[int]					       =					tokenizer.tokenize('こんにちは、世界。\nこんばんは、世界。'     )
      self.assertListEqual(__snake_case						,      ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。']     )
      self.assertListEqual(tokenizer.convert_tokens_to_ids(__snake_case     )						,      [3, 12, 10, 14, 4, 9, 12, 10, 14]     )







    def       lowercase_	(				self			:  Union[str, Any]     ):
      a						: Tuple					       =					self.tokenizer_class(self.vocab_file						,      word_tokenizer_type='mecab'     )
      self.assertIsNotNone(__snake_case     )

      a						: List[str]					       =					'こんにちは、世界。\nこんばんは、世界。'
      a						: Tuple					       =					tokenizer.tokenize(__snake_case     )
      self.assertListEqual(__snake_case						,      ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。']     )
      self.assertListEqual(tokenizer.convert_tokens_to_ids(__snake_case     )						,      [3, 12, 10, 14, 4, 9, 12, 10, 14]     )

      a						: Optional[int]					       =					os.path.join(self.tmpdirname						,      'tokenizer.bin'     )
      with open(__snake_case						,      'wb'     ) as handle:
        pickle.dump(__snake_case						,      __snake_case     )

      with open(__snake_case						,      'rb'     ) as handle:
        a						: Optional[Any]					       =					pickle.load(__snake_case     )

      a						: Tuple					       =					tokenizer_new.tokenize(__snake_case     )

      self.assertListEqual(__snake_case						,      __snake_case     )







    def       lowercase_	(				self			:  Dict     ):
      a						: List[str]					       =					MecabTokenizer(mecab_dic='ipadic'     )

      self.assertListEqual(
          tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '     )						,      ['アップルストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。']						,      )







    def       lowercase_	(				self			:  List[Any]     ):
      try:
        a						: int					       =					MecabTokenizer(mecab_dic='unidic_lite'     )
      except ModuleNotFoundError:
        return

      self.assertListEqual(
          tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '     )						,      ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。']						,      )







    def       lowercase_	(				self			:  Any     ):
      try:
        a						: Union[str, Any]					       =					MecabTokenizer(mecab_dic='unidic'     )
      except ModuleNotFoundError:
        return

      self.assertListEqual(
          tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '     )						,      ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。']						,      )







    def       lowercase_	(				self			:  str     ):
      a						: Tuple					       =					MecabTokenizer(do_lower_case=__snake_case						,      mecab_dic='ipadic'     )

      self.assertListEqual(
          tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '     )						,      ['アップルストア', 'で', 'iphone', '8', 'が', '発売', 'さ', 'れ', 'た', '。']						,      )







    def       lowercase_	(				self			:  Union[str, Any]     ):
      try:
        a						: Any					       =					MecabTokenizer(
            do_lower_case=__snake_case						,      normalize_text=__snake_case						,      mecab_option='-d /usr/local/lib/mecab/dic/jumandic'     )
      except RuntimeError:
        # if dict doesn't exist in the system, previous code raises this error.
        return

      self.assertListEqual(
          tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '     )						,      ['ｱｯﾌﾟﾙストア', 'で', 'iPhone', '８', 'が', '発売', 'さ', 'れた', '\u3000', '。']						,      )







    def       lowercase_	(				self			:  List[Any]     ):
      a						: Dict					       =					MecabTokenizer(normalize_text=__snake_case						,      mecab_dic='ipadic'     )

      self.assertListEqual(
          tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '     )						,      ['ｱｯﾌﾟﾙストア', 'で', 'iPhone', '８', 'が', '発売', 'さ', 'れ', 'た', '　', '。']						,      )







    @require_sudachi
    def       lowercase_	(				self			:  str     ):
      a						: Optional[int]					       =					self.tokenizer_class(self.vocab_file						,      word_tokenizer_type='sudachi'     )
      self.assertIsNotNone(__snake_case     )

      a						: List[Any]					       =					'こんにちは、世界。\nこんばんは、世界。'
      a						: int					       =					tokenizer.tokenize(__snake_case     )
      self.assertListEqual(__snake_case						,      ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。']     )
      self.assertListEqual(tokenizer.convert_tokens_to_ids(__snake_case     )						,      [3, 12, 10, 14, 4, 9, 12, 10, 14]     )

      a						: Tuple					       =					os.path.join(self.tmpdirname						,      'tokenizer.bin'     )
      with open(__snake_case						,      'wb'     ) as handle:
        pickle.dump(__snake_case						,      __snake_case     )

      with open(__snake_case						,      'rb'     ) as handle:
        a						: Optional[int]					       =					pickle.load(__snake_case     )

      a						: List[Any]					       =					tokenizer_new.tokenize(__snake_case     )

      self.assertListEqual(__snake_case						,      __snake_case     )







    @require_sudachi
    def       lowercase_	(				self			:  List[Any]     ):
      a						: Optional[Any]					       =					SudachiTokenizer(sudachi_dict_type='core'     )

      self.assertListEqual(
          tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '     )						,      [' ', '\t', 'アップル', 'ストア', 'で', 'iPhone', '8', ' ', 'が', ' ', ' ', '\n ', '発売', 'さ', 'れ', 'た', ' ', '。', ' ', ' ']						,      )







    @require_sudachi
    def       lowercase_	(				self			:  Any     ):
      a						: str					       =					SudachiTokenizer(sudachi_dict_type='core'						,      sudachi_split_mode='A'     )

      self.assertListEqual(tokenizer.tokenize('外国人参政権'     )						,      ['外国', '人', '参政', '権']     )







    @require_sudachi
    def       lowercase_	(				self			:  Optional[Any]     ):
      a						: Optional[int]					       =					SudachiTokenizer(sudachi_dict_type='core'						,      sudachi_split_mode='B'     )

      self.assertListEqual(tokenizer.tokenize('外国人参政権'     )						,      ['外国人', '参政権']     )







    @require_sudachi
    def       lowercase_	(				self			:  Optional[Any]     ):
      a						: Dict					       =					SudachiTokenizer(sudachi_dict_type='core'						,      sudachi_split_mode='C'     )

      self.assertListEqual(tokenizer.tokenize('外国人参政権'     )						,      ['外国人参政権']     )







    @require_sudachi
    def       lowercase_	(				self			:  Dict     ):
      a						: Optional[int]					       =					SudachiTokenizer(do_lower_case=__snake_case						,      sudachi_dict_type='core'     )

      self.assertListEqual(
          tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '     )						,      [' ', '\t', 'アップル', 'ストア', 'で', 'iphone', '8', ' ', 'が', ' ', ' ', '\n ', '発売', 'さ', 'れ', 'た', ' ', '。', ' ', ' ']						,      )







    @require_sudachi
    def       lowercase_	(				self			:  Tuple     ):
      a						: int					       =					SudachiTokenizer(normalize_text=__snake_case						,      sudachi_dict_type='core'     )

      self.assertListEqual(
          tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '     )						,      [' ', '\t', 'ｱｯﾌﾟﾙ', 'ストア', 'で', 'iPhone', '８', ' ', 'が', ' ', ' ', '\n ', '発売', 'さ', 'れ', 'た', '\u3000', '。', ' ', ' ']						,      )







    @require_sudachi
    def       lowercase_	(				self			:  Union[str, Any]     ):
      a						: List[str]					       =					SudachiTokenizer(trim_whitespace=__snake_case						,      sudachi_dict_type='core'     )

      self.assertListEqual(
          tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '     )						,      ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。']						,      )







    @require_jumanpp
    def       lowercase_	(				self			:  List[Any]     ):
      a						: Optional[int]					       =					self.tokenizer_class(self.vocab_file						,      word_tokenizer_type='jumanpp'     )
      self.assertIsNotNone(__snake_case     )

      a						: str					       =					'こんにちは、世界。\nこんばんは、世界。'
      a						: Tuple					       =					tokenizer.tokenize(__snake_case     )
      self.assertListEqual(__snake_case						,      ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。']     )
      self.assertListEqual(tokenizer.convert_tokens_to_ids(__snake_case     )						,      [3, 12, 10, 14, 4, 9, 12, 10, 14]     )

      a						: Optional[Any]					       =					os.path.join(self.tmpdirname						,      'tokenizer.bin'     )
      with open(__snake_case						,      'wb'     ) as handle:
        pickle.dump(__snake_case						,      __snake_case     )

      with open(__snake_case						,      'rb'     ) as handle:
        a						: List[str]					       =					pickle.load(__snake_case     )

      a						: Any					       =					tokenizer_new.tokenize(__snake_case     )

      self.assertListEqual(__snake_case						,      __snake_case     )







    @require_jumanpp
    def       lowercase_	(				self			:  List[str]     ):
      a						: Any					       =					JumanppTokenizer()

      self.assertListEqual(
          tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '     )						,      ['アップル', 'ストア', 'で', 'iPhone', '8', '\u3000', 'が', '\u3000', '\u3000', '\u3000', '発売', 'さ', 'れた', '\u3000', '。']						,      )







    @require_jumanpp
    def       lowercase_	(				self			:  List[str]     ):
      a						: List[Any]					       =					JumanppTokenizer(do_lower_case=__snake_case     )

      self.assertListEqual(
          tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '     )						,      ['アップル', 'ストア', 'で', 'iphone', '8', '\u3000', 'が', '\u3000', '\u3000', '\u3000', '発売', 'さ', 'れた', '\u3000', '。']						,      )







    @require_jumanpp
    def       lowercase_	(				self			:  Any     ):
      a						: List[Any]					       =					JumanppTokenizer(normalize_text=__snake_case     )

      self.assertListEqual(
          tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '     )						,      ['ｱ', 'ｯ', 'ﾌ', 'ﾟ', 'ﾙ', 'ストア', 'で', 'iPhone', '８', '\u3000', 'が', '\u3000', '\u3000', '\u3000', '発売', 'さ', 'れた', '\u3000', '。']						,      )







    @require_jumanpp
    def       lowercase_	(				self			:  Any     ):
      a						: str					       =					JumanppTokenizer(trim_whitespace=__snake_case     )

      self.assertListEqual(
          tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '     )						,      ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れた', '。']						,      )







    @require_jumanpp
    def       lowercase_	(				self			:  Tuple     ):
      a						: int					       =					JumanppTokenizer()

      self.assertListEqual(
          tokenizer.tokenize('ありがとうございますm(_ _)ｍ見つけるのが大変です。'     )						,      ['ありがとう', 'ございます', 'm(_ _)m', '見つける', 'の', 'が', '大変です', '。']						,      )







    def       lowercase_	(				self			:  Any     ):
      a						: int					       =					['[UNK]', '[CLS]', '[SEP]', 'こんにちは', 'こん', 'にちは', 'ばんは', '##こん', '##にちは', '##ばんは']

      a						: Optional[int]					       =					{}
      for i, token in enumerate(__snake_case     ):
        a						: Dict					       =					i
      a						: Optional[Any]					       =					WordpieceTokenizer(vocab=__snake_case						,      unk_token='[UNK]'     )

      self.assertListEqual(tokenizer.tokenize(''     )						,      []     )

      self.assertListEqual(tokenizer.tokenize('こんにちは'     )						,      ['こんにちは']     )

      self.assertListEqual(tokenizer.tokenize('こんばんは'     )						,      ['こん', '##ばんは']     )

      self.assertListEqual(tokenizer.tokenize('こんばんは こんばんにちは こんにちは'     )						,      ['こん', '##ばんは', '[UNK]', 'こんにちは']     )







    def       lowercase_	(				self			:  Tuple     ):
      a						: List[Any]					       =					BertJapaneseTokenizer.from_pretrained('nlp-waseda/roberta-base-japanese-with-auto-jumanpp'     )
      a						: List[Any]					       =					tokenizer.subword_tokenizer

      a						: List[str]					       =					subword_tokenizer.tokenize('国境 の 長い トンネル を 抜ける と 雪国 であった 。'     )
      self.assertListEqual(__snake_case						,      ['▁国境', '▁の', '▁長い', '▁トンネル', '▁を', '▁抜ける', '▁と', '▁雪', '国', '▁であった', '▁。']     )

      a						: Union[str, Any]					       =					subword_tokenizer.tokenize('こんばんは こんばん にち は こんにちは'     )
      self.assertListEqual(__snake_case						,      ['▁こん', 'ばん', 'は', '▁こん', 'ばん', '▁に', 'ち', '▁は', '▁こんにちは']     )







    def       lowercase_	(				self			:  Union[str, Any]     ):
      a						: Optional[Any]					       =					self.tokenizer_class.from_pretrained('cl-tohoku/bert-base-japanese'     )

      a						: Dict					       =					tokenizer.encode('ありがとう。'						,      add_special_tokens=__snake_case     )
      a						: str					       =					tokenizer.encode('どういたしまして。'						,      add_special_tokens=__snake_case     )

      a						: Optional[int]					       =					tokenizer.build_inputs_with_special_tokens(__snake_case     )
      a						: Union[str, Any]					       =					tokenizer.build_inputs_with_special_tokens(__snake_case						,      __snake_case     )

      # 2 is for "[CLS]", 3 is for "[SEP]"
      assert encoded_sentence == [2] + text + [3]
      assert encoded_pair == [2] + text + [3] + text_a + [3]

@custom_tokenizers
class 							a__( lowerCamelCase__		,			unittest.TestCase     ):
    lowercase__			=   BertJapaneseTokenizer
    lowercase__			=   False







    def       lowercase_	(				self			:  List[Any]     ):
      super().setUp()

      a						: List[Any]					       =					['[UNK]', '[CLS]', '[SEP]', 'こ', 'ん', 'に', 'ち', 'は', 'ば', '世', '界', '、', '。']

      a						: List[Any]					       =					os.path.join(self.tmpdirname						,      VOCAB_FILES_NAMES['vocab_file']     )
      with open(self.vocab_file						,      'w'						,      encoding='utf-8'     ) as vocab_writer:
        vocab_writer.write(''.join([x + '\n' for x in vocab_tokens]     )     )







    def       lowercase_	(				self			:  Optional[Any]						,      **__snake_case			:  List[Any]     ):
      return BertJapaneseTokenizer.from_pretrained(self.tmpdirname						,      subword_tokenizer_type='character'						,      **__snake_case     )







    def       lowercase_	(				self			:  Tuple						,      __snake_case			:  List[str]     ):
      a						: int					       =					'こんにちは、世界。 \nこんばんは、世界。'
      a						: Optional[Any]					       =					'こ ん に ち は 、 世 界 。 こ ん ば ん は 、 世 界 。'
      return input_text, output_text







    def       lowercase_	(				self			:  str     ):
      pass  # TODO add if relevant







    def       lowercase_	(				self			:  List[str]     ):
      pass  # TODO add if relevant







    def       lowercase_	(				self			:  Any     ):
      pass  # TODO add if relevant







    def       lowercase_	(				self			:  Any     ):
      a						: Optional[int]					       =					self.tokenizer_class(self.vocab_file						,      subword_tokenizer_type='character'     )

      a						: Tuple					       =					tokenizer.tokenize('こんにちは、世界。 \nこんばんは、世界。'     )
      self.assertListEqual(
          __snake_case						,      ['こ', 'ん', 'に', 'ち', 'は', '、', '世', '界', '。', 'こ', 'ん', 'ば', 'ん', 'は', '、', '世', '界', '。']     )
      self.assertListEqual(
          tokenizer.convert_tokens_to_ids(__snake_case     )						,      [3, 4, 5, 6, 7, 11, 9, 10, 12, 3, 4, 8, 4, 7, 11, 9, 10, 12]     )







    def       lowercase_	(				self			:  Any     ):
      a						: Union[str, Any]					       =					['[UNK]', '[CLS]', '[SEP]', 'こ', 'ん', 'に', 'ち', 'は', 'ば', '世', '界', '、', '。']

      a						: Optional[Any]					       =					{}
      for i, token in enumerate(__snake_case     ):
        a						: Tuple					       =					i
      a						: Optional[int]					       =					CharacterTokenizer(vocab=__snake_case						,      unk_token='[UNK]'     )

      self.assertListEqual(tokenizer.tokenize(''     )						,      []     )

      self.assertListEqual(tokenizer.tokenize('こんにちは'     )						,      ['こ', 'ん', 'に', 'ち', 'は']     )

      self.assertListEqual(tokenizer.tokenize('こんにちほ'     )						,      ['こ', 'ん', 'に', 'ち', '[UNK]']     )







    def       lowercase_	(				self			:  Tuple     ):
      a						: List[Any]					       =					self.tokenizer_class.from_pretrained('cl-tohoku/bert-base-japanese-char'     )

      a						: Optional[int]					       =					tokenizer.encode('ありがとう。'						,      add_special_tokens=__snake_case     )
      a						: List[str]					       =					tokenizer.encode('どういたしまして。'						,      add_special_tokens=__snake_case     )

      a						: Optional[int]					       =					tokenizer.build_inputs_with_special_tokens(__snake_case     )
      a						: Dict					       =					tokenizer.build_inputs_with_special_tokens(__snake_case						,      __snake_case     )

      # 2 is for "[CLS]", 3 is for "[SEP]"
      assert encoded_sentence == [2] + text + [3]
      assert encoded_pair == [2] + text + [3] + text_a + [3]

@custom_tokenizers
class 							a__( unittest.TestCase     ):







    def       lowercase_	(				self			:  List[str]     ):
      a						: List[Any]					       =					'cl-tohoku/bert-base-japanese'
      a						: Dict					       =					AutoTokenizer.from_pretrained(__snake_case     )
      self.assertIsInstance(__snake_case						,      __snake_case     )

class 							a__( unittest.TestCase     ):







    def       lowercase_	(				self			:  Union[str, Any]     ):
      a						: List[str]					       =					'cl-tohoku/bert-base-japanese'
      with self.assertLogs('transformers'						,      level='WARNING'     ) as cm:
        BertTokenizer.from_pretrained(__snake_case     )
        self.assertTrue(
            cm.records[0].message.startswith(
                'The tokenizer class you load from this checkpoint is not the same type as the class this function'
                ' is called from.'     )     )
      a						: Dict					       =					'bert-base-cased'
      with self.assertLogs('transformers'						,      level='WARNING'     ) as cm:
        BertJapaneseTokenizer.from_pretrained(__snake_case     )
        self.assertTrue(
            cm.records[0].message.startswith(
                'The tokenizer class you load from this checkpoint is not the same type as the class this function'
                ' is called from.'     )     )