



"""simple docstring"""


import logging
import os
import sys
import warnings
from dataclasses import dataclass, field
from random import randint
from typing import Optional

import datasets
import evaluate
import numpy as np
from datasets import DatasetDict, load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoFeatureExtractor,
    AutoModelForAudioClassification,
    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


snake_case_				     =       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.14.0""", """To fix: pip install -r examples/pytorch/audio-classification/requirements.txt""")

def  _lowerCAmelCase      (   lowercase_		,	lowercase_		,	lowercase_ = 16000						):
						UpperCAmelCase             = int(round(sample_rate * max_length						)						)
						if len(lowercase_						) <= sample_length:
												return wav
						UpperCAmelCase             = randint(0		,	len(lowercase_						) - sample_length - 1						)
						return wav[random_offset : random_offset + sample_length]







@dataclass
class       A_			:



						"""simple docstring"""
						__UpperCamelCase						=							field(default=SCREAMING_SNAKE_CASE_	,   metadata={"""help""": """Name of a dataset from the datasets package"""}				)
						__UpperCamelCase						=							field(
						    default=SCREAMING_SNAKE_CASE_	,   metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}				)
						__UpperCamelCase						=							field(
						    default=SCREAMING_SNAKE_CASE_	,   metadata={"""help""": """A file containing the training audio paths and labels."""}				)
						__UpperCamelCase						=							field(
						    default=SCREAMING_SNAKE_CASE_	,   metadata={"""help""": """A file containing the validation audio paths and labels."""}				)
						__UpperCamelCase						=							field(
						    default="""train"""	,   metadata={
						        """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'"""
						    }	,   )
						__UpperCamelCase						=							field(
						    default="""validation"""	,   metadata={
						        """help""": (
						            """The name of the training data set split to use (via the datasets library). Defaults to 'validation'"""
						        )
						    }	,   )
						__UpperCamelCase						=							field(
						    default="""audio"""	,   metadata={"""help""": """The name of the dataset column containing the audio data. Defaults to 'audio'"""}	,   )
						__UpperCamelCase						=							field(
						    default="""label"""	,   metadata={"""help""": """The name of the dataset column containing the labels. Defaults to 'label'"""}				)
						__UpperCamelCase						=							field(
						    default=SCREAMING_SNAKE_CASE_	,   metadata={
						        """help""": (
						            """For debugging purposes or quicker training, truncate the number of training examples to this """
						            """value if set."""
						        )
						    }	,   )
						__UpperCamelCase						=							field(
						    default=SCREAMING_SNAKE_CASE_	,   metadata={
						        """help""": (
						            """For debugging purposes or quicker training, truncate the number of evaluation examples to this """
						            """value if set."""
						        )
						    }	,   )
						__UpperCamelCase						=							field(
						    default=20	,   metadata={"""help""": """Audio clips will be randomly cut to this length during training if the value is set."""}	,   )







@dataclass
class       A_			:



						"""simple docstring"""
						__UpperCamelCase						=							field(
						    default="""facebook/wav2vec2-base"""	,   metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}	,   )
						__UpperCamelCase						=							field(
						    default=SCREAMING_SNAKE_CASE_	,   metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}				)
						__UpperCamelCase						=							field(
						    default=SCREAMING_SNAKE_CASE_	,   metadata={"""help""": """Where do you want to store the pretrained models downloaded from the Hub"""}				)
						__UpperCamelCase						=							field(
						    default="""main"""	,   metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""}	,   )
						__UpperCamelCase						=							field(
						    default=SCREAMING_SNAKE_CASE_	,   metadata={"""help""": """Name or path of preprocessor config."""}				)
						__UpperCamelCase						=							field(
						    default=SCREAMING_SNAKE_CASE_	,   metadata={"""help""": """Whether to freeze the feature encoder layers of the model."""}				)
						__UpperCamelCase						=							field(
						    default=SCREAMING_SNAKE_CASE_	,   metadata={"""help""": """Whether to generate an attention mask in the feature extractor."""}				)
						__UpperCamelCase						=							field(
						    default=SCREAMING_SNAKE_CASE_	,   metadata={
						        """help""": (
						            """Will use the token generated when running `huggingface-cli login` (necessary to use this script """
						            """with private models)."""
						        )
						    }	,   )
						__UpperCamelCase						=							field(
						    default=SCREAMING_SNAKE_CASE_	,   metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""}				)
						__UpperCamelCase						=							field(
						    default=SCREAMING_SNAKE_CASE_	,   metadata={"""help""": """Will enable to load a pretrained model whose head dimensions are different."""}	,   )






						def 	UpperCAmelCase__     (					self :Dict					)				->			Union[str, Any]:
												if not self.freeze_feature_extractor and self.freeze_feature_encoder:
																		warnings.warn(
																		    'The argument `--freeze_feature_extractor` is deprecated and '
																		    'will be removed in a future version. Use `--freeze_feature_encoder`'
																		    'instead. Setting `freeze_feature_encoder==True`.'   ,  lowercase_   ,  )
												if self.freeze_feature_extractor and not self.freeze_feature_encoder:
																		raise ValueError(
																		    'The argument `--freeze_feature_extractor` is deprecated and '
																		    'should not be used in combination with `--freeze_feature_encoder`.'
																		    'Only make use of `--freeze_feature_encoder`.'					)


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.

						UpperCAmelCase             = 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.
												UpperCAmelCase      ,    UpperCAmelCase      ,    UpperCAmelCase             = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]						)						)
						else:
												UpperCAmelCase      ,    UpperCAmelCase      ,    UpperCAmelCase             = 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_audio_classification'		,	lowercase_		,	lowercase_						)

						# 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()

						UpperCAmelCase             = training_args.get_process_log_level()
						logger.setLevel(lowercase_						)
						transformers.utils.logging.set_verbosity(lowercase_						)
						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}"""						)

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

						# Detecting last checkpoint.
						UpperCAmelCase             = None
						if os.path.isdir(training_args.output_dir						) and training_args.do_train and not training_args.overwrite_output_dir:
												UpperCAmelCase             = 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 train from scratch.'						)
												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.'						)

    # Initialize our dataset and prepare it for the audio classification task.
						UpperCAmelCase             = DatasetDict()
						UpperCAmelCase             = load_dataset(
						    data_args.dataset_name		,	data_args.dataset_config_name		,	split=data_args.train_split_name		,	use_auth_token=True if model_args.use_auth_token else None		,	)
						UpperCAmelCase             = load_dataset(
						    data_args.dataset_name		,	data_args.dataset_config_name		,	split=data_args.eval_split_name		,	use_auth_token=True if model_args.use_auth_token else None		,	)

						if data_args.audio_column_name not in raw_datasets["train"].column_names:
												raise ValueError(
												    F"""--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. """
												    'Make sure to set `--audio_column_name` to the correct audio column - one of '
												    F"""{', '.join(raw_datasets['train'].column_names						)}."""						)

						if data_args.label_column_name not in raw_datasets["train"].column_names:
												raise ValueError(
												    F"""--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. """
												    'Make sure to set `--label_column_name` to the correct text column - one of '
												    F"""{', '.join(raw_datasets['train'].column_names						)}."""						)

						# Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over
						# transformer outputs in the classifier, but it doesn't always lead to better accuracy
						UpperCAmelCase             = AutoFeatureExtractor.from_pretrained(
						    model_args.feature_extractor_name or model_args.model_name_or_path		,	return_attention_mask=model_args.attention_mask		,	cache_dir=model_args.cache_dir		,	revision=model_args.model_revision		,	use_auth_token=True if model_args.use_auth_token else None		,	)

						# `datasets` takes care of automatically loading and resampling the audio,
						# so we just need to set the correct target sampling rate.
						UpperCAmelCase             = raw_datasets.cast_column(
						    data_args.audio_column_name		,	datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate						)						)

						UpperCAmelCase             = feature_extractor.model_input_names[0]

						def train_transforms(lowercase_						):
												UpperCAmelCase             = []
												for audio in batch[data_args.audio_column_name]:
																		UpperCAmelCase             = random_subsample(
																		    audio['array']		,	max_length=data_args.max_length_seconds		,	sample_rate=feature_extractor.sampling_rate						)
																		subsampled_wavs.append(lowercase_						)
												UpperCAmelCase             = feature_extractor(lowercase_		,	sampling_rate=feature_extractor.sampling_rate						)
												UpperCAmelCase             = {model_input_name: inputs.get(lowercase_						)}
												UpperCAmelCase             = list(batch[data_args.label_column_name]						)

												return output_batch

						def val_transforms(lowercase_						):
												UpperCAmelCase             = [audio['array'] for audio in batch[data_args.audio_column_name]]
												UpperCAmelCase             = feature_extractor(lowercase_		,	sampling_rate=feature_extractor.sampling_rate						)
												UpperCAmelCase             = {model_input_name: inputs.get(lowercase_						)}
												UpperCAmelCase             = list(batch[data_args.label_column_name]						)

												return output_batch

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

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

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

						UpperCAmelCase             = AutoConfig.from_pretrained(
						    model_args.config_name or model_args.model_name_or_path		,	num_labels=len(lowercase_						)		,	labelaid=lowercase_		,	idalabel=lowercase_		,	finetuning_task='audio-classification'		,	cache_dir=model_args.cache_dir		,	revision=model_args.model_revision		,	use_auth_token=True if model_args.use_auth_token else None		,	)
						UpperCAmelCase             = AutoModelForAudioClassification.from_pretrained(
						    model_args.model_name_or_path		,	from_tf=bool('.ckpt' in model_args.model_name_or_path						)		,	config=lowercase_		,	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		,	)

						# freeze the convolutional waveform encoder
						if model_args.freeze_feature_encoder:
												model.freeze_feature_encoder()

						if training_args.do_train:
												if data_args.max_train_samples is not None:
																		UpperCAmelCase             = (
																		    raw_datasets['train'].shuffle(seed=training_args.seed						).select(range(data_args.max_train_samples						)						)
																		)
												# Set the training transforms
												raw_datasets["train"].set_transform(lowercase_		,	output_all_columns=lowercase_						)

						if training_args.do_eval:
												if data_args.max_eval_samples is not None:
																		UpperCAmelCase             = (
																		    raw_datasets['eval'].shuffle(seed=training_args.seed						).select(range(data_args.max_eval_samples						)						)
																		)
												# Set the validation transforms
												raw_datasets["eval"].set_transform(lowercase_		,	output_all_columns=lowercase_						)

						# Initialize our trainer
						UpperCAmelCase             = Trainer(
						    model=lowercase_		,	args=lowercase_		,	train_dataset=raw_datasets['train'] if training_args.do_train else None		,	eval_dataset=raw_datasets['eval'] if training_args.do_eval else None		,	compute_metrics=lowercase_		,	tokenizer=lowercase_		,	)

						# Training
						if training_args.do_train:
												UpperCAmelCase             = None
												if training_args.resume_from_checkpoint is not None:
																		UpperCAmelCase             = training_args.resume_from_checkpoint
												elif last_checkpoint is not None:
																		UpperCAmelCase             = last_checkpoint
												UpperCAmelCase             = trainer.train(resume_from_checkpoint=lowercase_						)
												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:
												UpperCAmelCase             = trainer.evaluate()
												trainer.log_metrics('eval'		,	lowercase_						)
												trainer.save_metrics('eval'		,	lowercase_						)

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


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_        = BertJapaneseTokenizer
  a_        = False
  a_        = True






  def 				lowercase		(				self :		Optional[Any]     )							->						List[str]:
     super().setUp()

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

     __lowerCAmelCase								=	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 :		List[Any]					,  lowerCAmelCase_ :		Tuple     )							->						str:
     __lowerCAmelCase								=	'こんにちは、世界。 \nこんばんは、世界。'
     __lowerCAmelCase								=	'こんにちは 、 世界 。 こんばんは 、 世界 。'
     return input_text, output_text






  def 				lowercase		(				self :		List[Any]					,  lowerCAmelCase_ :		str     )							->						Dict:
     __lowerCAmelCase	,	__lowerCAmelCase								=	self.get_input_output_texts(lowerCAmelCase_     )
     __lowerCAmelCase								=	tokenizer.encode(lowerCAmelCase_					,  add_special_tokens=lowerCAmelCase_     )
     __lowerCAmelCase								=	tokenizer.decode(lowerCAmelCase_					,  clean_up_tokenization_spaces=lowerCAmelCase_     )
     return text, ids






  def 				lowercase		(				self :		List[str]     )							->						Optional[int]:
     pass  # TODO add if relevant






  def 				lowercase		(				self :		Optional[Any]     )							->						Optional[Any]:
     pass  # TODO add if relevant






  def 				lowercase		(				self :		Union[str, Any]     )							->						Any:
     pass  # TODO add if relevant






  def 				lowercase		(				self :		Dict     )							->						Tuple:
     __lowerCAmelCase								=	self.tokenizer_class(self.vocab_file     )

     __lowerCAmelCase								=	tokenizer.tokenize('こんにちは、世界。\nこんばんは、世界。'     )
     self.assertListEqual(lowerCAmelCase_					,  ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。']     )
     self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase_     )					,  [3, 1_2, 1_0, 1_4, 4, 9, 1_2, 1_0, 1_4]     )






  def 				lowercase		(				self :		List[str]     )							->						List[str]:
     __lowerCAmelCase								=	self.tokenizer_class(self.vocab_file					,  word_tokenizer_type='mecab'     )
     self.assertIsNotNone(lowerCAmelCase_     )

     __lowerCAmelCase								=	'こんにちは、世界。\nこんばんは、世界。'
     __lowerCAmelCase								=	tokenizer.tokenize(lowerCAmelCase_     )
     self.assertListEqual(lowerCAmelCase_					,  ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。']     )
     self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase_     )					,  [3, 1_2, 1_0, 1_4, 4, 9, 1_2, 1_0, 1_4]     )

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

     with open(lowerCAmelCase_					,  'rb'     ) as handle:
        __lowerCAmelCase								=	pickle.load(lowerCAmelCase_     )

     __lowerCAmelCase								=	tokenizer_new.tokenize(lowerCAmelCase_     )

     self.assertListEqual(lowerCAmelCase_					,  lowerCAmelCase_     )






  def 				lowercase		(				self :		Dict     )							->						Tuple:
     __lowerCAmelCase								=	MecabTokenizer(mecab_dic='ipadic'     )

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






  def 				lowercase		(				self :		List[Any]     )							->						int:
     try:
        __lowerCAmelCase								=	MecabTokenizer(mecab_dic='unidic_lite'     )
     except ModuleNotFoundError:
        return

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






  def 				lowercase		(				self :		Tuple     )							->						Optional[Any]:
     try:
        __lowerCAmelCase								=	MecabTokenizer(mecab_dic='unidic'     )
     except ModuleNotFoundError:
        return

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






  def 				lowercase		(				self :		Tuple     )							->						Union[str, Any]:
     __lowerCAmelCase								=	MecabTokenizer(do_lower_case=lowerCAmelCase_					,  mecab_dic='ipadic'     )

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






  def 				lowercase		(				self :		Union[str, Any]     )							->						Optional[Any]:
     try:
        __lowerCAmelCase								=	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 				lowercase		(				self :		Any     )							->						Union[str, Any]:
     __lowerCAmelCase								=	MecabTokenizer(normalize_text=lowerCAmelCase_					,  mecab_dic='ipadic'     )

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






  @require_sudachi
  def 				lowercase		(				self :		List[str]     )							->						List[str]:
     __lowerCAmelCase								=	self.tokenizer_class(self.vocab_file					,  word_tokenizer_type='sudachi'     )
     self.assertIsNotNone(lowerCAmelCase_     )

     __lowerCAmelCase								=	'こんにちは、世界。\nこんばんは、世界。'
     __lowerCAmelCase								=	tokenizer.tokenize(lowerCAmelCase_     )
     self.assertListEqual(lowerCAmelCase_					,  ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。']     )
     self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase_     )					,  [3, 1_2, 1_0, 1_4, 4, 9, 1_2, 1_0, 1_4]     )

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

     with open(lowerCAmelCase_					,  'rb'     ) as handle:
        __lowerCAmelCase								=	pickle.load(lowerCAmelCase_     )

     __lowerCAmelCase								=	tokenizer_new.tokenize(lowerCAmelCase_     )

     self.assertListEqual(lowerCAmelCase_					,  lowerCAmelCase_     )






  @require_sudachi
  def 				lowercase		(				self :		Union[str, Any]     )							->						List[str]:
     __lowerCAmelCase								=	SudachiTokenizer(sudachi_dict_type='core'     )

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






  @require_sudachi
  def 				lowercase		(				self :		Tuple     )							->						Optional[Any]:
     __lowerCAmelCase								=	SudachiTokenizer(sudachi_dict_type='core'					,  sudachi_split_mode='A'     )

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






  @require_sudachi
  def 				lowercase		(				self :		Tuple     )							->						List[Any]:
     __lowerCAmelCase								=	SudachiTokenizer(sudachi_dict_type='core'					,  sudachi_split_mode='B'     )

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






  @require_sudachi
  def 				lowercase		(				self :		List[str]     )							->						Union[str, Any]:
     __lowerCAmelCase								=	SudachiTokenizer(sudachi_dict_type='core'					,  sudachi_split_mode='C'     )

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






  @require_sudachi
  def 				lowercase		(				self :		Dict     )							->						List[str]:
     __lowerCAmelCase								=	SudachiTokenizer(do_lower_case=lowerCAmelCase_					,  sudachi_dict_type='core'     )

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






  @require_sudachi
  def 				lowercase		(				self :		Union[str, Any]     )							->						List[Any]:
     __lowerCAmelCase								=	SudachiTokenizer(normalize_text=lowerCAmelCase_					,  sudachi_dict_type='core'     )

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






  @require_sudachi
  def 				lowercase		(				self :		int     )							->						str:
     __lowerCAmelCase								=	SudachiTokenizer(trim_whitespace=lowerCAmelCase_					,  sudachi_dict_type='core'     )

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






  @require_jumanpp
  def 				lowercase		(				self :		Union[str, Any]     )							->						Any:
     __lowerCAmelCase								=	self.tokenizer_class(self.vocab_file					,  word_tokenizer_type='jumanpp'     )
     self.assertIsNotNone(lowerCAmelCase_     )

     __lowerCAmelCase								=	'こんにちは、世界。\nこんばんは、世界。'
     __lowerCAmelCase								=	tokenizer.tokenize(lowerCAmelCase_     )
     self.assertListEqual(lowerCAmelCase_					,  ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。']     )
     self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase_     )					,  [3, 1_2, 1_0, 1_4, 4, 9, 1_2, 1_0, 1_4]     )

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

     with open(lowerCAmelCase_					,  'rb'     ) as handle:
        __lowerCAmelCase								=	pickle.load(lowerCAmelCase_     )

     __lowerCAmelCase								=	tokenizer_new.tokenize(lowerCAmelCase_     )

     self.assertListEqual(lowerCAmelCase_					,  lowerCAmelCase_     )






  @require_jumanpp
  def 				lowercase		(				self :		List[Any]     )							->						Optional[Any]:
     __lowerCAmelCase								=	JumanppTokenizer()

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






  @require_jumanpp
  def 				lowercase		(				self :		Any     )							->						Union[str, Any]:
     __lowerCAmelCase								=	JumanppTokenizer(do_lower_case=lowerCAmelCase_     )

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






  @require_jumanpp
  def 				lowercase		(				self :		Dict     )							->						Dict:
     __lowerCAmelCase								=	JumanppTokenizer(normalize_text=lowerCAmelCase_     )

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






  @require_jumanpp
  def 				lowercase		(				self :		List[str]     )							->						List[str]:
     __lowerCAmelCase								=	JumanppTokenizer(trim_whitespace=lowerCAmelCase_     )

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






  @require_jumanpp
  def 				lowercase		(				self :		Any     )							->						Any:
     __lowerCAmelCase								=	JumanppTokenizer()

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






  def 				lowercase		(				self :		Any     )							->						str:
     __lowerCAmelCase								=	['[UNK]', '[CLS]', '[SEP]', 'こんにちは', 'こん', 'にちは', 'ばんは', '##こん', '##にちは', '##ばんは']

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

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

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

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

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






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

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

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






  def 				lowercase		(				self :		int     )							->						str:
     __lowerCAmelCase								=	self.tokenizer_class.from_pretrained('cl-tohoku/bert-base-japanese'     )

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

     __lowerCAmelCase								=	tokenizer.build_inputs_with_special_tokens(lowerCAmelCase_     )
     __lowerCAmelCase								=	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_        = BertJapaneseTokenizer
  a_        = False






  def 				lowercase		(				self :		Optional[Any]     )							->						Tuple:
     super().setUp()

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

     __lowerCAmelCase								=	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 :		str					,  **lowerCAmelCase_ :		Tuple     )							->						Union[str, Any]:
     return BertJapaneseTokenizer.from_pretrained(self.tmpdirname					,  subword_tokenizer_type='character'					,  **lowerCAmelCase_     )






  def 				lowercase		(				self :		Tuple					,  lowerCAmelCase_ :		Tuple     )							->						Optional[int]:
     __lowerCAmelCase								=	'こんにちは、世界。 \nこんばんは、世界。'
     __lowerCAmelCase								=	'こ ん に ち は 、 世 界 。 こ ん ば ん は 、 世 界 。'
     return input_text, output_text






  def 				lowercase		(				self :		Dict     )							->						str:
     pass  # TODO add if relevant






  def 				lowercase		(				self :		Any     )							->						str:
     pass  # TODO add if relevant






  def 				lowercase		(				self :		List[Any]     )							->						int:
     pass  # TODO add if relevant






  def 				lowercase		(				self :		str     )							->						str:
     __lowerCAmelCase								=	self.tokenizer_class(self.vocab_file					,  subword_tokenizer_type='character'     )

     __lowerCAmelCase								=	tokenizer.tokenize('こんにちは、世界。 \nこんばんは、世界。'     )
     self.assertListEqual(
         lowerCAmelCase_					,  ['こ', 'ん', 'に', 'ち', 'は', '、', '世', '界', '。', 'こ', 'ん', 'ば', 'ん', 'は', '、', '世', '界', '。']     )
     self.assertListEqual(
         tokenizer.convert_tokens_to_ids(lowerCAmelCase_     )					,  [3, 4, 5, 6, 7, 1_1, 9, 1_0, 1_2, 3, 4, 8, 4, 7, 1_1, 9, 1_0, 1_2]     )






  def 				lowercase		(				self :		str     )							->						Optional[int]:
     __lowerCAmelCase								=	['[UNK]', '[CLS]', '[SEP]', 'こ', 'ん', 'に', 'ち', 'は', 'ば', '世', '界', '、', '。']

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

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

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

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






  def 				lowercase		(				self :		int     )							->						str:
     __lowerCAmelCase								=	self.tokenizer_class.from_pretrained('cl-tohoku/bert-base-japanese-char'     )

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

     __lowerCAmelCase								=	tokenizer.build_inputs_with_special_tokens(lowerCAmelCase_     )
     __lowerCAmelCase								=	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 				lowercase		(				self :		str     )							->						Union[str, Any]:
     __lowerCAmelCase								=	'cl-tohoku/bert-base-japanese'
     __lowerCAmelCase								=	AutoTokenizer.from_pretrained(lowerCAmelCase_     )
     self.assertIsInstance(lowerCAmelCase_					,  lowerCAmelCase_     )





class 				_UpperCAmelCase    (    unittest.TestCase    ):

  """simple docstring"""


  def 				lowercase		(				self :		List[str]     )							->						Optional[int]:
     __lowerCAmelCase								=	'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.'     )     )
     __lowerCAmelCase								=	'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.'     )     )

