




# This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/

import gc
import random
import tempfile
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    ControlNetModel,
    DDIMScheduler,
    StableDiffusionControlNetImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel
from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import (
    PipelineKarrasSchedulerTesterMixin,
    PipelineLatentTesterMixin,
    PipelineTesterMixin,
)


enable_full_determinism()







class __snake_case			(			a ,  a ,  a ,  unittest.TestCase		):
   UpperCAmelCase__  :    List[Any]          =  StableDiffusionControlNetImgaImgPipeline
   UpperCAmelCase__  :    Optional[Any]          =  TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''}
   UpperCAmelCase__  :    Optional[Any]          =  TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
   UpperCAmelCase__  :    Union[str, Any]          =  IMAGE_TO_IMAGE_IMAGE_PARAMS.union({'''control_image'''}		)
   UpperCAmelCase__  :    Optional[Any]          =  IMAGE_TO_IMAGE_IMAGE_PARAMS







   def lowerCamelCase						(      self		:						int):

        """simple docstring"""


        torch.manual_seed(0)
        UpperCAmelCase_          =							UNetaDConditionModel(
            block_out_channels=(32, 64)					,						layers_per_block=2					,						sample_size=32					,						in_channels=4					,						out_channels=4					,						down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')					,						up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')					,						cross_attention_dim=32					,						)
        torch.manual_seed(0)
        UpperCAmelCase_          =							ControlNetModel(
            block_out_channels=(32, 64)					,						layers_per_block=2					,						in_channels=4					,						down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')					,						cross_attention_dim=32					,						conditioning_embedding_out_channels=(16, 32)					,						)
        torch.manual_seed(0)
        UpperCAmelCase_          =							DDIMScheduler(
            beta_start=0.0_0_0_8_5					,						beta_end=0.0_1_2					,						beta_schedule='''scaled_linear'''					,						clip_sample=_snake_case					,						set_alpha_to_one=_snake_case					,						)
        torch.manual_seed(0)
        UpperCAmelCase_          =							AutoencoderKL(
            block_out_channels=[32, 64]					,						in_channels=3					,						out_channels=3					,						down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']					,						up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']					,						latent_channels=4					,						)
        torch.manual_seed(0)
        UpperCAmelCase_          =							CLIPTextConfig(
            bos_token_id=0					,						eos_token_id=2					,						hidden_size=32					,						intermediate_size=37					,						layer_norm_eps=1e-05					,						num_attention_heads=4					,						num_hidden_layers=5					,						pad_token_id=1					,						vocab_size=1000					,						)
        UpperCAmelCase_          =							CLIPTextModel(_snake_case)
        UpperCAmelCase_          =							CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''')

        UpperCAmelCase_          =							{
            '''unet''': unet,
            '''controlnet''': controlnet,
            '''scheduler''': scheduler,
            '''vae''': vae,
            '''text_encoder''': text_encoder,
            '''tokenizer''': tokenizer,
            '''safety_checker''': None,
            '''feature_extractor''': None,
        }
        return components







   def lowerCamelCase						(      self		:						Union[str, Any]					,						_snake_case		:						Any					,						_snake_case		:						Dict=0):

        """simple docstring"""


        if str(_snake_case).startswith('''mps'''):
             UpperCAmelCase_          =							torch.manual_seed(_snake_case)
        else:
             UpperCAmelCase_          =							torch.Generator(device=_snake_case).manual_seed(_snake_case)

        UpperCAmelCase_          =							2
        UpperCAmelCase_          =							randn_tensor(
            (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor)					,						generator=_snake_case					,						device=torch.device(_snake_case)					,						)
        UpperCAmelCase_          =							floats_tensor(control_image.shape					,						rng=random.Random(_snake_case)).to(_snake_case)
        UpperCAmelCase_          =							image.cpu().permute(0					,						2					,						3					,						1)[0]
        UpperCAmelCase_          =							Image.fromarray(np.uinta(_snake_case)).convert('''RGB''').resize((64, 64))
        UpperCAmelCase_          =							{
            '''prompt''': '''A painting of a squirrel eating a burger''',
            '''generator''': generator,
            '''num_inference_steps''': 2,
            '''guidance_scale''': 6.0,
            '''output_type''': '''numpy''',
            '''image''': image,
            '''control_image''': control_image,
        }

        return inputs







   def lowerCamelCase						(      self		:						Any):

        """simple docstring"""


        return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3)







   @unittest.skipIf(
       torch_device != '''cuda''' or not is_xformers_available()					,						reason='''XFormers attention is only available with CUDA and `xformers` installed'''					,						)
   def lowerCamelCase						(      self		:						Any):

        """simple docstring"""


        self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3)







   def lowerCamelCase						(      self		:						Optional[Any]):

        """simple docstring"""


        self._test_inference_batch_single_identical(expected_max_diff=2e-3)







class __snake_case			(			a ,  a ,  unittest.TestCase		):
   UpperCAmelCase__  :    str          =  StableDiffusionControlNetImgaImgPipeline
   UpperCAmelCase__  :    List[str]          =  TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''}
   UpperCAmelCase__  :    Optional[Any]          =  TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
   UpperCAmelCase__  :    str          =  frozenset([]		)  # TO_DO: add image_params once refactored VaeImageProcessor.preprocess







   def lowerCamelCase						(      self		:						str):

        """simple docstring"""


        torch.manual_seed(0)
        UpperCAmelCase_          =							UNetaDConditionModel(
            block_out_channels=(32, 64)					,						layers_per_block=2					,						sample_size=32					,						in_channels=4					,						out_channels=4					,						down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')					,						up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')					,						cross_attention_dim=32					,						)
        torch.manual_seed(0)

        def init_weights(_snake_case		:						Optional[int]):
             if isinstance(_snake_case					,						torch.nn.Convad):
                  torch.nn.init.normal(m.weight)
                  m.bias.data.fill_(1.0)

        UpperCAmelCase_          =							ControlNetModel(
            block_out_channels=(32, 64)					,						layers_per_block=2					,						in_channels=4					,						down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')					,						cross_attention_dim=32					,						conditioning_embedding_out_channels=(16, 32)					,						)
        controlneta.controlnet_down_blocks.apply(_snake_case)

        torch.manual_seed(0)
        UpperCAmelCase_          =							ControlNetModel(
            block_out_channels=(32, 64)					,						layers_per_block=2					,						in_channels=4					,						down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')					,						cross_attention_dim=32					,						conditioning_embedding_out_channels=(16, 32)					,						)
        controlneta.controlnet_down_blocks.apply(_snake_case)

        torch.manual_seed(0)
        UpperCAmelCase_          =							DDIMScheduler(
            beta_start=0.0_0_0_8_5					,						beta_end=0.0_1_2					,						beta_schedule='''scaled_linear'''					,						clip_sample=_snake_case					,						set_alpha_to_one=_snake_case					,						)
        torch.manual_seed(0)
        UpperCAmelCase_          =							AutoencoderKL(
            block_out_channels=[32, 64]					,						in_channels=3					,						out_channels=3					,						down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']					,						up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']					,						latent_channels=4					,						)
        torch.manual_seed(0)
        UpperCAmelCase_          =							CLIPTextConfig(
            bos_token_id=0					,						eos_token_id=2					,						hidden_size=32					,						intermediate_size=37					,						layer_norm_eps=1e-05					,						num_attention_heads=4					,						num_hidden_layers=5					,						pad_token_id=1					,						vocab_size=1000					,						)
        UpperCAmelCase_          =							CLIPTextModel(_snake_case)
        UpperCAmelCase_          =							CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''')

        UpperCAmelCase_          =							MultiControlNetModel([controlneta, controlneta])

        UpperCAmelCase_          =							{
            '''unet''': unet,
            '''controlnet''': controlnet,
            '''scheduler''': scheduler,
            '''vae''': vae,
            '''text_encoder''': text_encoder,
            '''tokenizer''': tokenizer,
            '''safety_checker''': None,
            '''feature_extractor''': None,
        }
        return components







   def lowerCamelCase						(      self		:						int					,						_snake_case		:						Union[str, Any]					,						_snake_case		:						str=0):

        """simple docstring"""


        if str(_snake_case).startswith('''mps'''):
             UpperCAmelCase_          =							torch.manual_seed(_snake_case)
        else:
             UpperCAmelCase_          =							torch.Generator(device=_snake_case).manual_seed(_snake_case)

        UpperCAmelCase_          =							2

        UpperCAmelCase_          =							[
            randn_tensor(
                (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor)					,						generator=_snake_case					,						device=torch.device(_snake_case)					,						),
            randn_tensor(
                (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor)					,						generator=_snake_case					,						device=torch.device(_snake_case)					,						),
        ]

        UpperCAmelCase_          =							floats_tensor(control_image[0].shape					,						rng=random.Random(_snake_case)).to(_snake_case)
        UpperCAmelCase_          =							image.cpu().permute(0					,						2					,						3					,						1)[0]
        UpperCAmelCase_          =							Image.fromarray(np.uinta(_snake_case)).convert('''RGB''').resize((64, 64))
        UpperCAmelCase_          =							{
            '''prompt''': '''A painting of a squirrel eating a burger''',
            '''generator''': generator,
            '''num_inference_steps''': 2,
            '''guidance_scale''': 6.0,
            '''output_type''': '''numpy''',
            '''image''': image,
            '''control_image''': control_image,
        }

        return inputs







   def lowerCamelCase						(      self		:						Optional[Any]):

        """simple docstring"""


        UpperCAmelCase_          =							self.get_dummy_components()
        UpperCAmelCase_          =							self.pipeline_class(**_snake_case)
        pipe.to(_snake_case)

        UpperCAmelCase_          =							1_0.0
        UpperCAmelCase_          =							4

        UpperCAmelCase_          =							self.get_dummy_inputs(_snake_case)
        UpperCAmelCase_          =							steps
        UpperCAmelCase_          =							scale
        UpperCAmelCase_          =							pipe(**_snake_case)[0]

        UpperCAmelCase_          =							self.get_dummy_inputs(_snake_case)
        UpperCAmelCase_          =							steps
        UpperCAmelCase_          =							scale
        UpperCAmelCase_          =							pipe(**_snake_case					,						control_guidance_start=0.1					,						control_guidance_end=0.2)[0]

        UpperCAmelCase_          =							self.get_dummy_inputs(_snake_case)
        UpperCAmelCase_          =							steps
        UpperCAmelCase_          =							scale
        UpperCAmelCase_          =							pipe(**_snake_case					,						control_guidance_start=[0.1, 0.3]					,						control_guidance_end=[0.2, 0.7])[0]

        UpperCAmelCase_          =							self.get_dummy_inputs(_snake_case)
        UpperCAmelCase_          =							steps
        UpperCAmelCase_          =							scale
        UpperCAmelCase_          =							pipe(**_snake_case					,						control_guidance_start=0.4					,						control_guidance_end=[0.5, 0.8])[0]

        # make sure that all outputs are different
        assert np.sum(np.abs(output_a - output_a)) > 1e-3
        assert np.sum(np.abs(output_a - output_a)) > 1e-3
        assert np.sum(np.abs(output_a - output_a)) > 1e-3







   def lowerCamelCase						(      self		:						Dict):

        """simple docstring"""


        return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3)







   @unittest.skipIf(
       torch_device != '''cuda''' or not is_xformers_available()					,						reason='''XFormers attention is only available with CUDA and `xformers` installed'''					,						)
   def lowerCamelCase						(      self		:						int):

        """simple docstring"""


        self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3)







   def lowerCamelCase						(      self		:						int):

        """simple docstring"""


        self._test_inference_batch_single_identical(expected_max_diff=2e-3)







   def lowerCamelCase						(      self		:						Optional[int]):

        """simple docstring"""


        UpperCAmelCase_          =							self.get_dummy_components()
        UpperCAmelCase_          =							self.pipeline_class(**_snake_case)
        pipe.to(_snake_case)
        pipe.set_progress_bar_config(disable=_snake_case)
        with tempfile.TemporaryDirectory() as tmpdir:
             try:
                  # save_pretrained is not implemented for Multi-ControlNet
                  pipe.save_pretrained(_snake_case)
             except NotImplementedError:
                  pass







@slow
@require_torch_gpu
class __snake_case			(			unittest.TestCase		):







   def lowerCamelCase						(      self		:						Optional[int]):

        """simple docstring"""


        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()







   def lowerCamelCase						(      self		:						Optional[int]):

        """simple docstring"""


        UpperCAmelCase_          =							ControlNetModel.from_pretrained('''lllyasviel/sd-controlnet-canny''')

        UpperCAmelCase_          =							StableDiffusionControlNetImgaImgPipeline.from_pretrained(
            '''runwayml/stable-diffusion-v1-5'''					,						safety_checker=_snake_case					,						controlnet=_snake_case)
        pipe.enable_model_cpu_offload()
        pipe.set_progress_bar_config(disable=_snake_case)

        UpperCAmelCase_          =							torch.Generator(device='''cpu''').manual_seed(0)
        UpperCAmelCase_          =							'''evil space-punk bird'''
        UpperCAmelCase_          =							load_image(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png''').resize((512, 512))
        UpperCAmelCase_          =							load_image(
            '''https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png''').resize((512, 512))

        UpperCAmelCase_          =							pipe(
            _snake_case					,						_snake_case					,						control_image=_snake_case					,						generator=_snake_case					,						output_type='''np'''					,						num_inference_steps=50					,						strength=0.6					,						)

        UpperCAmelCase_          =							output.images[0]

        assert image.shape == (512, 512, 3)

        UpperCAmelCase_          =							load_numpy(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy''')

        assert np.abs(expected_image - image).max() < 9e-2







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.'''						)						)