'''simple docstring'''




import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import evaluate
import numpy as np
import torch
from datasets import load_dataset
from PIL import Image
from torchvision.transforms import (
    CenterCrop,
    Compose,
    Normalize,
    RandomHorizontalFlip,
    RandomResizedCrop,
    Resize,
    ToTensor,
)

import transformers
from transformers import (
    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    AutoModelForImageClassification,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
__UpperCAmelCase     							=logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.31.0")

require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-classification/requirements.txt")

__UpperCAmelCase     							=list(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING.keys())
__UpperCAmelCase     							=tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)






def __lowerCAmelCase (							UpperCamelCase__				)	->    Optional[int]:



    with open(UpperCamelCase__				,  '''rb'''				) as f:
        __lowerCamelCase		=  Image.open(UpperCamelCase__				)
        return im.convert('''RGB'''				)




@dataclass
class     a__      :
     lowerCamelCase  :     Optional[str]							=field(
         default=_UpperCAmelCase							,   metadata={
             "help": "Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub)."
         }							,   )
     lowerCamelCase  :     Optional[str]							=field(
         default=_UpperCAmelCase							,   metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} )
     lowerCamelCase  :     Optional[str]							=field(default=_UpperCAmelCase							,   metadata={"help": "A folder containing the training data."} )
     lowerCamelCase  :     Optional[str]							=field(default=_UpperCAmelCase							,   metadata={"help": "A folder containing the validation data."} )
     lowerCamelCase  :     Optional[float]							=field(
         default=0.15							,   metadata={"help": "Percent to split off of train for validation."} )
     lowerCamelCase  :     Optional[int]							=field(
         default=_UpperCAmelCase							,   metadata={
             "help": (
                 "For debugging purposes or quicker training, truncate the number of training examples to this "
                 "value if set."
             )
         }							,   )
     lowerCamelCase  :     Optional[int]							=field(
         default=_UpperCAmelCase							,   metadata={
             "help": (
                 "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
                 "value if set."
             )
         }							,   )






     def    SCREAMING_SNAKE_CASE__   ( self		:		List[str]    ):





         """simple docstring"""



         if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
             raise ValueError(
                 '''You must specify either a dataset name from the hub or a train and/or validation directory.'''    )




@dataclass
class     a__      :
     lowerCamelCase  :     str							=field(
         default="google/vit-base-patch16-224-in21k"							,   metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}							,   )
     lowerCamelCase  :     Optional[str]							=field(
         default=_UpperCAmelCase							,   metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(_UpperCAmelCase )}							,   )
     lowerCamelCase  :     Optional[str]							=field(
         default=_UpperCAmelCase							,   metadata={"help": "Pretrained config name or path if not the same as model_name"} )
     lowerCamelCase  :     Optional[str]							=field(
         default=_UpperCAmelCase							,   metadata={"help": "Where do you want to store the pretrained models downloaded from s3"} )
     lowerCamelCase  :     str							=field(
         default="main"							,   metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}							,   )
     lowerCamelCase  :     str							=field(default=_UpperCAmelCase							,   metadata={"help": "Name or path of preprocessor config."} )
     lowerCamelCase  :     bool							=field(
         default=_UpperCAmelCase							,   metadata={
             "help": (
                 "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
                 "with private models)."
             )
         }							,   )
     lowerCamelCase  :     bool							=field(
         default=_UpperCAmelCase							,   metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."}							,   )






def __lowerCAmelCase (							UpperCamelCase__				)	->    Dict:
    __lowerCamelCase		=  torch.stack([example['''pixel_values'''] for example in examples]				)
    __lowerCamelCase		=  torch.tensor([example['''labels'''] for example in examples]				)
    return {"pixel_values": pixel_values, "labels": labels}






def __lowerCAmelCase (							)	->    Optional[int]:
    __lowerCamelCase		=  HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)				)
    if len(sys.argv				) == 2 and sys.argv[1].endswith('''.json'''				):
        # If we pass only one argument to the script and it's the path to a json file,
        # let's parse it to get our arguments.
        __lowerCamelCase	,  __lowerCamelCase	,  __lowerCamelCase		=  parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]				)				)
    else:
        __lowerCamelCase	,  __lowerCamelCase	,  __lowerCamelCase		=  parser.parse_args_into_dataclasses()

    # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
    # information sent is the one passed as arguments along with your Python/PyTorch versions.
    send_example_telemetry('''run_image_classification'''				,  UpperCamelCase__				,  UpperCamelCase__				)

    # Setup logging
    logging.basicConfig(
        format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''				,  datefmt='''%m/%d/%Y %H:%M:%S'''				,  handlers=[logging.StreamHandler(sys.stdout				)]				,  )

    if training_args.should_log:
        # The default of training_args.log_level is passive, so we set log level at info here to have that default.
        transformers.utils.logging.set_verbosity_info()

    __lowerCamelCase		=  training_args.get_process_log_level()
    logger.setLevel(UpperCamelCase__				)
    transformers.utils.logging.set_verbosity(UpperCamelCase__				)
    transformers.utils.logging.enable_default_handler()
    transformers.utils.logging.enable_explicit_format()

    # Log on each process the small summary:
    logger.warning(
        f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
        + f"""distributed training: {bool(training_args.local_rank != -1				)}, 16-bits training: {training_args.fpaa}"""				)
    logger.info(f"""Training/evaluation parameters {training_args}"""				)

    # Detecting last checkpoint.
    __lowerCamelCase		=  None
    if os.path.isdir(training_args.output_dir				) and training_args.do_train and not training_args.overwrite_output_dir:
        __lowerCamelCase		=  get_last_checkpoint(training_args.output_dir				)
        if last_checkpoint is None and len(os.listdir(training_args.output_dir				)				) > 0:
            raise ValueError(
                f"""Output directory ({training_args.output_dir}) already exists and is not empty. """
                '''Use --overwrite_output_dir to overcome.'''				)
        elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
            logger.info(
                f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
                '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'''				)

    # Set seed before initializing model.
    set_seed(training_args.seed				)

    # Initialize our dataset and prepare it for the 'image-classification' task.
    if data_args.dataset_name is not None:
        __lowerCamelCase		=  load_dataset(
            data_args.dataset_name				,  data_args.dataset_config_name				,  cache_dir=model_args.cache_dir				,  task='''image-classification'''				,  use_auth_token=True if model_args.use_auth_token else None				,  )
    else:
        __lowerCamelCase		=  {}
        if data_args.train_dir is not None:
            __lowerCamelCase		=  os.path.join(data_args.train_dir				,  '''**'''				)
        if data_args.validation_dir is not None:
            __lowerCamelCase		=  os.path.join(data_args.validation_dir				,  '''**'''				)
        __lowerCamelCase		=  load_dataset(
            '''imagefolder'''				,  data_files=UpperCamelCase__				,  cache_dir=model_args.cache_dir				,  task='''image-classification'''				,  )

    # If we don't have a validation split, split off a percentage of train as validation.
    __lowerCamelCase		=  None if '''validation''' in dataset.keys() else data_args.train_val_split
    if isinstance(data_args.train_val_split				,  UpperCamelCase__				) and data_args.train_val_split > 0.0:
        __lowerCamelCase		=  dataset['''train'''].train_test_split(data_args.train_val_split				)
        __lowerCamelCase		=  split['''train''']
        __lowerCamelCase		=  split['''test''']

    # Prepare label mappings.
    # We'll include these in the model's config to get human readable labels in the Inference API.
    __lowerCamelCase		=  dataset['''train'''].features['''labels'''].names
    __lowerCamelCase	,  __lowerCamelCase		=  {}, {}
    for i, label in enumerate(UpperCamelCase__				):
        __lowerCamelCase		=  str(UpperCamelCase__				)
        __lowerCamelCase		=  label

    # Load the accuracy metric from the datasets package
    __lowerCamelCase		=  evaluate.load('''accuracy'''				)

    # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
    # predictions and label_ids field) and has to return a dictionary string to float.
    def compute_metrics(UpperCamelCase__				):
        return metric.compute(predictions=np.argmax(p.predictions				,  axis=1				)				,  references=p.label_ids				)

    __lowerCamelCase		=  AutoConfig.from_pretrained(
        model_args.config_name or model_args.model_name_or_path				,  num_labels=len(UpperCamelCase__				)				,  labelaid=UpperCamelCase__				,  idalabel=UpperCamelCase__				,  finetuning_task='''image-classification'''				,  cache_dir=model_args.cache_dir				,  revision=model_args.model_revision				,  use_auth_token=True if model_args.use_auth_token else None				,  )
    __lowerCamelCase		=  AutoModelForImageClassification.from_pretrained(
        model_args.model_name_or_path				,  from_tf=bool('''.ckpt''' in model_args.model_name_or_path				)				,  config=UpperCamelCase__				,  cache_dir=model_args.cache_dir				,  revision=model_args.model_revision				,  use_auth_token=True if model_args.use_auth_token else None				,  ignore_mismatched_sizes=model_args.ignore_mismatched_sizes				,  )
    __lowerCamelCase		=  AutoImageProcessor.from_pretrained(
        model_args.image_processor_name or model_args.model_name_or_path				,  cache_dir=model_args.cache_dir				,  revision=model_args.model_revision				,  use_auth_token=True if model_args.use_auth_token else None				,  )

    # Define torchvision transforms to be applied to each image.
    if "shortest_edge" in image_processor.size:
        __lowerCamelCase		=  image_processor.size['''shortest_edge''']
    else:
        __lowerCamelCase		=  (image_processor.size['''height'''], image_processor.size['''width'''])
    __lowerCamelCase		=  Normalize(mean=image_processor.image_mean				,  std=image_processor.image_std				)
    __lowerCamelCase		=  Compose(
        [
            RandomResizedCrop(UpperCamelCase__				),
            RandomHorizontalFlip(),
            ToTensor(),
            normalize,
        ]				)
    __lowerCamelCase		=  Compose(
        [
            Resize(UpperCamelCase__				),
            CenterCrop(UpperCamelCase__				),
            ToTensor(),
            normalize,
        ]				)

    def train_transforms(UpperCamelCase__				):
        __lowerCamelCase		=  [
            _train_transforms(pil_img.convert('''RGB'''				)				) for pil_img in example_batch['''image''']
        ]
        return example_batch

    def val_transforms(UpperCamelCase__				):
        __lowerCamelCase		=  [_val_transforms(pil_img.convert('''RGB'''				)				) for pil_img in example_batch['''image''']]
        return example_batch

    if training_args.do_train:
        if "train" not in dataset:
            raise ValueError('''--do_train requires a train dataset'''				)
        if data_args.max_train_samples is not None:
            __lowerCamelCase		=  (
                dataset['''train'''].shuffle(seed=training_args.seed				).select(range(data_args.max_train_samples				)				)
            )
        # Set the training transforms
        dataset["train"].set_transform(UpperCamelCase__				)

    if training_args.do_eval:
        if "validation" not in dataset:
            raise ValueError('''--do_eval requires a validation dataset'''				)
        if data_args.max_eval_samples is not None:
            __lowerCamelCase		=  (
                dataset['''validation'''].shuffle(seed=training_args.seed				).select(range(data_args.max_eval_samples				)				)
            )
        # Set the validation transforms
        dataset["validation"].set_transform(UpperCamelCase__				)

    # Initalize our trainer
    __lowerCamelCase		=  Trainer(
        model=UpperCamelCase__				,  args=UpperCamelCase__				,  train_dataset=dataset['''train'''] if training_args.do_train else None				,  eval_dataset=dataset['''validation'''] if training_args.do_eval else None				,  compute_metrics=UpperCamelCase__				,  tokenizer=UpperCamelCase__				,  data_collator=UpperCamelCase__				,  )

    # Training
    if training_args.do_train:
        __lowerCamelCase		=  None
        if training_args.resume_from_checkpoint is not None:
            __lowerCamelCase		=  training_args.resume_from_checkpoint
        elif last_checkpoint is not None:
            __lowerCamelCase		=  last_checkpoint
        __lowerCamelCase		=  trainer.train(resume_from_checkpoint=UpperCamelCase__				)
        trainer.save_model()
        trainer.log_metrics('''train'''				,  train_result.metrics				)
        trainer.save_metrics('''train'''				,  train_result.metrics				)
        trainer.save_state()

    # Evaluation
    if training_args.do_eval:
        __lowerCamelCase		=  trainer.evaluate()
        trainer.log_metrics('''eval'''				,  UpperCamelCase__				)
        trainer.save_metrics('''eval'''				,  UpperCamelCase__				)

    # Write model card and (optionally) push to hub
    __lowerCamelCase		=  {
        '''finetuned_from''': model_args.model_name_or_path,
        '''tasks''': '''image-classification''',
        '''dataset''': data_args.dataset_name,
        '''tags''': ['''image-classification''', '''vision'''],
    }
    if training_args.push_to_hub:
        trainer.push_to_hub(**UpperCamelCase__				)
    else:
        trainer.create_model_card(**UpperCamelCase__				)


if __name__ == "__main__":
  main()

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    _UpperCamelCase      (						_UpperCAmelCase						,unittest.TestCase ):


			"""simple docstring"""






			__a  : List[Any]			 =						BertJapaneseTokenizer
			__a  : Any			 =						False
			__a  : Optional[int]			 =						True





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Optional[Any]:

							'''simple docstring'''


							super().setUp()

							__lowercase 			=							[
							    '''[UNK]''',
							    '''[CLS]''',
							    '''[SEP]''',
							    '''こんにちは''',
							    '''こん''',
							    '''にちは''',
							    '''ばんは''',
							    '''##こん''',
							    '''##にちは''',
							    '''##ばんは''',
							    '''世界''',
							    '''##世界''',
							    '''、''',
							    '''##、''',
							    '''。''',
							    '''##。''',
							]

							__lowercase 			=							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        _SCREAMING_SNAKE_CASE			(   self      ,   lowerCAmelCase__						)     ->					str:

							'''simple docstring'''


							__lowercase 			=							'''こんにちは、世界。 \nこんばんは、世界。'''
							__lowercase 			=							'''こんにちは 、 世界 。 こんばんは 、 世界 。'''
							return input_text, output_text





			def        _SCREAMING_SNAKE_CASE			(   self      ,   lowerCAmelCase__						)     ->					Dict:

							'''simple docstring'''


							__lowercase			,     __lowercase 			=							self.get_input_output_texts(lowerCAmelCase__						)
							__lowercase 			=							tokenizer.encode(lowerCAmelCase__      ,   add_special_tokens=lowerCAmelCase__						)
							__lowercase 			=							tokenizer.decode(lowerCAmelCase__      ,   clean_up_tokenization_spaces=lowerCAmelCase__						)
							return text, ids





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					List[Any]:

							'''simple docstring'''


							pass  # TODO add if relevant





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Union[str, Any]:

							'''simple docstring'''


							pass  # TODO add if relevant





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Tuple:

							'''simple docstring'''


							pass  # TODO add if relevant





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					List[str]:

							'''simple docstring'''


							__lowercase 			=							self.tokenizer_class(self.vocab_file						)

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





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Tuple:

							'''simple docstring'''


							__lowercase 			=							self.tokenizer_class(self.vocab_file      ,   word_tokenizer_type='''mecab'''						)
							self.assertIsNotNone(lowerCAmelCase__						)

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

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

							with open(lowerCAmelCase__      ,   '''rb'''						) as handle:
											__lowercase 			=							pickle.load(lowerCAmelCase__						)

							__lowercase 			=							tokenizer_new.tokenize(lowerCAmelCase__						)

							self.assertListEqual(lowerCAmelCase__      ,   lowerCAmelCase__						)





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Dict:

							'''simple docstring'''


							__lowercase 			=							MecabTokenizer(mecab_dic='''ipadic'''						)

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





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					int:

							'''simple docstring'''


							try:
											__lowercase 			=							MecabTokenizer(mecab_dic='''unidic_lite'''						)
							except ModuleNotFoundError:
											return

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





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					List[Any]:

							'''simple docstring'''


							try:
											__lowercase 			=							MecabTokenizer(mecab_dic='''unidic'''						)
							except ModuleNotFoundError:
											return

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





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

							'''simple docstring'''


							__lowercase 			=							MecabTokenizer(do_lower_case=lowerCAmelCase__      ,   mecab_dic='''ipadic'''						)

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





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					str:

							'''simple docstring'''


							try:
											__lowercase 			=							MecabTokenizer(
											    do_lower_case=lowerCAmelCase__      ,   normalize_text=lowerCAmelCase__      ,   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        _SCREAMING_SNAKE_CASE			(   self						)     ->					List[Any]:

							'''simple docstring'''


							__lowercase 			=							MecabTokenizer(normalize_text=lowerCAmelCase__      ,   mecab_dic='''ipadic'''						)

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





			@require_sudachi
			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Dict:

							'''simple docstring'''


							__lowercase 			=							self.tokenizer_class(self.vocab_file      ,   word_tokenizer_type='''sudachi'''						)
							self.assertIsNotNone(lowerCAmelCase__						)

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

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

							with open(lowerCAmelCase__      ,   '''rb'''						) as handle:
											__lowercase 			=							pickle.load(lowerCAmelCase__						)

							__lowercase 			=							tokenizer_new.tokenize(lowerCAmelCase__						)

							self.assertListEqual(lowerCAmelCase__      ,   lowerCAmelCase__						)





			@require_sudachi
			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Union[str, Any]:

							'''simple docstring'''


							__lowercase 			=							SudachiTokenizer(sudachi_dict_type='''core'''						)

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





			@require_sudachi
			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Optional[int]:

							'''simple docstring'''


							__lowercase 			=							SudachiTokenizer(sudachi_dict_type='''core'''      ,   sudachi_split_mode='''A'''						)

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





			@require_sudachi
			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					str:

							'''simple docstring'''


							__lowercase 			=							SudachiTokenizer(sudachi_dict_type='''core'''      ,   sudachi_split_mode='''B'''						)

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





			@require_sudachi
			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					int:

							'''simple docstring'''


							__lowercase 			=							SudachiTokenizer(sudachi_dict_type='''core'''      ,   sudachi_split_mode='''C'''						)

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





			@require_sudachi
			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					List[Any]:

							'''simple docstring'''


							__lowercase 			=							SudachiTokenizer(do_lower_case=lowerCAmelCase__      ,   sudachi_dict_type='''core'''						)

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





			@require_sudachi
			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Any:

							'''simple docstring'''


							__lowercase 			=							SudachiTokenizer(normalize_text=lowerCAmelCase__      ,   sudachi_dict_type='''core'''						)

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





			@require_sudachi
			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Any:

							'''simple docstring'''


							__lowercase 			=							SudachiTokenizer(trim_whitespace=lowerCAmelCase__      ,   sudachi_dict_type='''core'''						)

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





			@require_jumanpp
			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					List[Any]:

							'''simple docstring'''


							__lowercase 			=							self.tokenizer_class(self.vocab_file      ,   word_tokenizer_type='''jumanpp'''						)
							self.assertIsNotNone(lowerCAmelCase__						)

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

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

							with open(lowerCAmelCase__      ,   '''rb'''						) as handle:
											__lowercase 			=							pickle.load(lowerCAmelCase__						)

							__lowercase 			=							tokenizer_new.tokenize(lowerCAmelCase__						)

							self.assertListEqual(lowerCAmelCase__      ,   lowerCAmelCase__						)





			@require_jumanpp
			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					List[str]:

							'''simple docstring'''


							__lowercase 			=							JumanppTokenizer()

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





			@require_jumanpp
			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					List[str]:

							'''simple docstring'''


							__lowercase 			=							JumanppTokenizer(do_lower_case=lowerCAmelCase__						)

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





			@require_jumanpp
			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					int:

							'''simple docstring'''


							__lowercase 			=							JumanppTokenizer(normalize_text=lowerCAmelCase__						)

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





			@require_jumanpp
			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Optional[int]:

							'''simple docstring'''


							__lowercase 			=							JumanppTokenizer(trim_whitespace=lowerCAmelCase__						)

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





			@require_jumanpp
			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Tuple:

							'''simple docstring'''


							__lowercase 			=							JumanppTokenizer()

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





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Any:

							'''simple docstring'''


							__lowercase 			=							['''[UNK]''', '''[CLS]''', '''[SEP]''', '''こんにちは''', '''こん''', '''にちは''', '''ばんは''', '''##こん''', '''##にちは''', '''##ばんは''']

							__lowercase 			=							{}
							for i, token in enumerate(lowerCAmelCase__						):
											__lowercase 			=							i
							__lowercase 			=							WordpieceTokenizer(vocab=lowerCAmelCase__      ,   unk_token='''[UNK]'''						)

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

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

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

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





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Tuple:

							'''simple docstring'''


							__lowercase 			=							BertJapaneseTokenizer.from_pretrained('''nlp-waseda/roberta-base-japanese-with-auto-jumanpp'''						)
							__lowercase 			=							tokenizer.subword_tokenizer

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

							__lowercase 			=							subword_tokenizer.tokenize('''こんばんは こんばん にち は こんにちは'''						)
							self.assertListEqual(lowerCAmelCase__      ,   ['''▁こん''', '''ばん''', '''は''', '''▁こん''', '''ばん''', '''▁に''', '''ち''', '''▁は''', '''▁こんにちは''']						)





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

							'''simple docstring'''


							__lowercase 			=							self.tokenizer_class.from_pretrained('''cl-tohoku/bert-base-japanese'''						)

							__lowercase 			=							tokenizer.encode('''ありがとう。'''      ,   add_special_tokens=lowerCAmelCase__						)
							__lowercase 			=							tokenizer.encode('''どういたしまして。'''      ,   add_special_tokens=lowerCAmelCase__						)

							__lowercase 			=							tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__						)
							__lowercase 			=							tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__      ,   lowerCAmelCase__						)

							# 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    _UpperCamelCase      (						_UpperCAmelCase						,unittest.TestCase ):


			"""simple docstring"""






			__a  : Union[str, Any]			 =						BertJapaneseTokenizer
			__a  : Tuple			 =						False





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					str:

							'''simple docstring'''


							super().setUp()

							__lowercase 			=							['''[UNK]''', '''[CLS]''', '''[SEP]''', '''こ''', '''ん''', '''に''', '''ち''', '''は''', '''ば''', '''世''', '''界''', '''、''', '''。''']

							__lowercase 			=							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        _SCREAMING_SNAKE_CASE			(   self      ,   **lowerCAmelCase__						)     ->					Dict:

							'''simple docstring'''


							return BertJapaneseTokenizer.from_pretrained(self.tmpdirname      ,   subword_tokenizer_type='''character'''      ,   **lowerCAmelCase__						)





			def        _SCREAMING_SNAKE_CASE			(   self      ,   lowerCAmelCase__						)     ->					List[str]:

							'''simple docstring'''


							__lowercase 			=							'''こんにちは、世界。 \nこんばんは、世界。'''
							__lowercase 			=							'''こ ん に ち は 、 世 界 。 こ ん ば ん は 、 世 界 。'''
							return input_text, output_text





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Union[str, Any]:

							'''simple docstring'''


							pass  # TODO add if relevant





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Optional[Any]:

							'''simple docstring'''


							pass  # TODO add if relevant





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Optional[Any]:

							'''simple docstring'''


							pass  # TODO add if relevant





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Union[str, Any]:

							'''simple docstring'''


							__lowercase 			=							self.tokenizer_class(self.vocab_file      ,   subword_tokenizer_type='''character'''						)

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





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Dict:

							'''simple docstring'''


							__lowercase 			=							['''[UNK]''', '''[CLS]''', '''[SEP]''', '''こ''', '''ん''', '''に''', '''ち''', '''は''', '''ば''', '''世''', '''界''', '''、''', '''。''']

							__lowercase 			=							{}
							for i, token in enumerate(lowerCAmelCase__						):
											__lowercase 			=							i
							__lowercase 			=							CharacterTokenizer(vocab=lowerCAmelCase__      ,   unk_token='''[UNK]'''						)

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

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

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





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Union[str, Any]:

							'''simple docstring'''


							__lowercase 			=							self.tokenizer_class.from_pretrained('''cl-tohoku/bert-base-japanese-char'''						)

							__lowercase 			=							tokenizer.encode('''ありがとう。'''      ,   add_special_tokens=lowerCAmelCase__						)
							__lowercase 			=							tokenizer.encode('''どういたしまして。'''      ,   add_special_tokens=lowerCAmelCase__						)

							__lowercase 			=							tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__						)
							__lowercase 			=							tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__      ,   lowerCAmelCase__						)

							# 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    _UpperCamelCase      (						unittest.TestCase ):


			"""simple docstring"""






			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Optional[Any]:

							'''simple docstring'''


							__lowercase 			=							'''cl-tohoku/bert-base-japanese'''
							__lowercase 			=							AutoTokenizer.from_pretrained(lowerCAmelCase__						)
							self.assertIsInstance(lowerCAmelCase__      ,   lowerCAmelCase__						)




class    _UpperCamelCase      (						unittest.TestCase ):


			"""simple docstring"""






			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Tuple:

							'''simple docstring'''


							__lowercase 			=							'''cl-tohoku/bert-base-japanese'''
							with self.assertLogs('''transformers'''      ,   level='''WARNING'''						) as cm:
											BertTokenizer.from_pretrained(lowerCAmelCase__						)
											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.'''						)						)
							__lowercase 			=							'''bert-base-cased'''
							with self.assertLogs('''transformers'''      ,   level='''WARNING'''						) as cm:
											BertJapaneseTokenizer.from_pretrained(lowerCAmelCase__						)
											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.'''						)						)