





# 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 					__a      (lowercase_       ,		lowercase_       ,		lowercase_       ,		unittest.TestCase     ):
							__a					:   List[Any]									=       StableDiffusionControlNetImgaImgPipeline
							__a					:   Any									=       TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''}
							__a					:   Any									=       TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
							__a					:   Tuple									=       IMAGE_TO_IMAGE_IMAGE_PARAMS.union({"control_image"}     )
							__a					:   Tuple									=       IMAGE_TO_IMAGE_IMAGE_PARAMS

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







													"""simple docstring"""
													torch.manual_seed(0   )
													UpperCAmelCase_			:      Optional[Any]     						=  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_			:      Tuple     						=  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_			:      Optional[int]     						=  DDIMScheduler(
													    beta_start=0.0_0_0_8_5       ,     beta_end=0.0_1_2       ,     beta_schedule='''scaled_linear'''       ,     clip_sample=__magic_name__       ,     set_alpha_to_one=__magic_name__       ,     )
													torch.manual_seed(0   )
													UpperCAmelCase_			:      Optional[int]     						=  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_			:      List[str]     						=  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=10_00       ,     )
													UpperCAmelCase_			:      List[str]     						=  CLIPTextModel(__magic_name__   )
													UpperCAmelCase_			:      List[str]     						=  CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''   )

													UpperCAmelCase_			:      Union[str, Any]     						=  {
													    '''unet''': unet,
													    '''controlnet''': controlnet,
													    '''scheduler''': scheduler,
													    '''vae''': vae,
													    '''text_encoder''': text_encoder,
													    '''tokenizer''': tokenizer,
													    '''safety_checker''': None,
													    '''feature_extractor''': None,
													}
													return components

							def     UpperCAmelCase__	(							self							:     Union[str, Any]       ,     __magic_name__							:     Tuple       ,     __magic_name__							:     Optional[Any]=0   )					->       List[str]:







													"""simple docstring"""
													if str(__magic_name__   ).startswith('''mps'''   ):
																			UpperCAmelCase_			:      int     						=  torch.manual_seed(__magic_name__   )
													else:
																			UpperCAmelCase_			:      Union[str, Any]     						=  torch.Generator(device=__magic_name__   ).manual_seed(__magic_name__   )

													UpperCAmelCase_			:      Tuple     						=  2
													UpperCAmelCase_			:      List[Any]     						=  randn_tensor(
													    (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor)       ,     generator=__magic_name__       ,     device=torch.device(__magic_name__   )       ,     )
													UpperCAmelCase_			:      List[Any]     						=  floats_tensor(control_image.shape       ,     rng=random.Random(__magic_name__   )   ).to(__magic_name__   )
													UpperCAmelCase_			:      Optional[Any]     						=  image.cpu().permute(0       ,     2       ,     3       ,     1   )[0]
													UpperCAmelCase_			:      Any     						=  Image.fromarray(np.uinta(__magic_name__   )   ).convert('''RGB'''   ).resize((64, 64)   )
													UpperCAmelCase_			:      Optional[Any]     						=  {
													    '''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     UpperCAmelCase__	(							self							:     Optional[int]   )					->       List[str]:







													"""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     UpperCAmelCase__	(							self							:     Optional[Any]   )					->       Union[str, Any]:







													"""simple docstring"""
													self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3   )



							def     UpperCAmelCase__	(							self							:     Union[str, Any]   )					->       Optional[int]:







													"""simple docstring"""
													self._test_inference_batch_single_identical(expected_max_diff=2E-3   )





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

							def     UpperCAmelCase__	(							self							:     List[Any]   )					->       Tuple:







													"""simple docstring"""
													torch.manual_seed(0   )
													UpperCAmelCase_			:      Union[str, Any]     						=  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(__magic_name__							:     Optional[int]   ):
																			if isinstance(__magic_name__       ,     torch.nn.Convad   ):
																									torch.nn.init.normal(m.weight   )
																									m.bias.data.fill_(1.0   )

													UpperCAmelCase_			:      List[str]     						=  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(__magic_name__   )

													torch.manual_seed(0   )
													UpperCAmelCase_			:      List[str]     						=  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(__magic_name__   )

													torch.manual_seed(0   )
													UpperCAmelCase_			:      Union[str, Any]     						=  DDIMScheduler(
													    beta_start=0.0_0_0_8_5       ,     beta_end=0.0_1_2       ,     beta_schedule='''scaled_linear'''       ,     clip_sample=__magic_name__       ,     set_alpha_to_one=__magic_name__       ,     )
													torch.manual_seed(0   )
													UpperCAmelCase_			:      List[str]     						=  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_			:      Optional[Any]     						=  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=10_00       ,     )
													UpperCAmelCase_			:      Any     						=  CLIPTextModel(__magic_name__   )
													UpperCAmelCase_			:      int     						=  CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''   )

													UpperCAmelCase_			:      List[str]     						=  MultiControlNetModel([controlneta, controlneta]   )

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

							def     UpperCAmelCase__	(							self							:     Optional[int]       ,     __magic_name__							:     Any       ,     __magic_name__							:     Optional[int]=0   )					->       Optional[int]:







													"""simple docstring"""
													if str(__magic_name__   ).startswith('''mps'''   ):
																			UpperCAmelCase_			:      Dict     						=  torch.manual_seed(__magic_name__   )
													else:
																			UpperCAmelCase_			:      Union[str, Any]     						=  torch.Generator(device=__magic_name__   ).manual_seed(__magic_name__   )

													UpperCAmelCase_			:      List[Any]     						=  2

													UpperCAmelCase_			:      Union[str, Any]     						=  [
													    randn_tensor(
													        (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor)       ,     generator=__magic_name__       ,     device=torch.device(__magic_name__   )       ,     ),
													    randn_tensor(
													        (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor)       ,     generator=__magic_name__       ,     device=torch.device(__magic_name__   )       ,     ),
													]

													UpperCAmelCase_			:      List[Any]     						=  floats_tensor(control_image[0].shape       ,     rng=random.Random(__magic_name__   )   ).to(__magic_name__   )
													UpperCAmelCase_			:      int     						=  image.cpu().permute(0       ,     2       ,     3       ,     1   )[0]
													UpperCAmelCase_			:      List[str]     						=  Image.fromarray(np.uinta(__magic_name__   )   ).convert('''RGB'''   ).resize((64, 64)   )
													UpperCAmelCase_			:      List[Any]     						=  {
													    '''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     UpperCAmelCase__	(							self							:     List[str]   )					->       Tuple:







													"""simple docstring"""
													UpperCAmelCase_			:      Optional[int]     						=  self.get_dummy_components()
													UpperCAmelCase_			:      str     						=  self.pipeline_class(**__magic_name__   )
													pipe.to(__magic_name__   )

													UpperCAmelCase_			:      List[str]     						=  1_0.0
													UpperCAmelCase_			:      List[Any]     						=  4

													UpperCAmelCase_			:      Optional[Any]     						=  self.get_dummy_inputs(__magic_name__   )
													UpperCAmelCase_			:      List[str]     						=  steps
													UpperCAmelCase_			:      Optional[Any]     						=  scale
													UpperCAmelCase_			:      List[Any]     						=  pipe(**__magic_name__   )[0]

													UpperCAmelCase_			:      List[str]     						=  self.get_dummy_inputs(__magic_name__   )
													UpperCAmelCase_			:      List[Any]     						=  steps
													UpperCAmelCase_			:      Dict     						=  scale
													UpperCAmelCase_			:      List[Any]     						=  pipe(**__magic_name__       ,     control_guidance_start=0.1       ,     control_guidance_end=0.2   )[0]

													UpperCAmelCase_			:      List[Any]     						=  self.get_dummy_inputs(__magic_name__   )
													UpperCAmelCase_			:      Union[str, Any]     						=  steps
													UpperCAmelCase_			:      Optional[Any]     						=  scale
													UpperCAmelCase_			:      str     						=  pipe(**__magic_name__       ,     control_guidance_start=[0.1, 0.3]       ,     control_guidance_end=[0.2, 0.7]   )[0]

													UpperCAmelCase_			:      Any     						=  self.get_dummy_inputs(__magic_name__   )
													UpperCAmelCase_			:      List[str]     						=  steps
													UpperCAmelCase_			:      List[Any]     						=  scale
													UpperCAmelCase_			:      Tuple     						=  pipe(**__magic_name__       ,     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     UpperCAmelCase__	(							self							:     Any   )					->       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     UpperCAmelCase__	(							self							:     Optional[Any]   )					->       Optional[Any]:







													"""simple docstring"""
													self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3   )

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







													"""simple docstring"""
													self._test_inference_batch_single_identical(expected_max_diff=2E-3   )



							def     UpperCAmelCase__	(							self							:     Dict   )					->       int:







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





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

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







													"""simple docstring"""
													super().tearDown()
													gc.collect()
													torch.cuda.empty_cache()



							def     UpperCAmelCase__	(							self							:     List[Any]   )					->       Optional[int]:







													"""simple docstring"""
													UpperCAmelCase_			:      Any     						=  ControlNetModel.from_pretrained('''lllyasviel/sd-controlnet-canny'''   )

													UpperCAmelCase_			:      Union[str, Any]     						=  StableDiffusionControlNetImgaImgPipeline.from_pretrained(
													    '''runwayml/stable-diffusion-v1-5'''       ,     safety_checker=__magic_name__       ,     controlnet=__magic_name__   )
													pipe.enable_model_cpu_offload()
													pipe.set_progress_bar_config(disable=__magic_name__   )

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

													UpperCAmelCase_			:      str     						=  pipe(
													    __magic_name__       ,     __magic_name__       ,     control_image=__magic_name__       ,     generator=__magic_name__       ,     output_type='''np'''       ,     num_inference_steps=50       ,     strength=0.6       ,     )

													UpperCAmelCase_			:      List[Any]     						=  output.images[0]

													assert image.shape == (5_12, 5_12, 3)

													UpperCAmelCase_			:      Dict     						=  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












'''simple docstring'''







import io
import os
import unicodedata
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


snake_case_     :       str						=  logging.get_logger(__name__)

snake_case_     :       int						=  "▁"

snake_case_     :       str						=  {"vocab_file": "vocab.txt", "sentencepiece_model_ckpt": "sentencepiece.bpe.model"}

snake_case_     :       int						=  {
    "sentencepiece_model_file": "sentencepiece.bpe.model",
    "vocab_file": "vocab.txt",
}

snake_case_     :       Optional[Any]						=  {
    "vocab_file": {
        "ernie-m-base": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt",
        "ernie-m-large": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt",
    },
    "sentencepiece_model_file": {
        "ernie-m-base": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model",
        "ernie-m-large": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model",
    },
}

snake_case_     :       Dict						=  {
    "ernie-m-base": 5_14,
    "ernie-m-large": 5_14,
}

snake_case_     :       Any						=  {
    "ernie-m-base": {"do_lower_case": False},
    "ernie-m-large": {"do_lower_case": False},
}


class 					__a      (lowerCamelCase     ):
							__a					:   List[str]									=       ["input_ids"]

							__a					:   Union[str, Any]									=       VOCAB_FILES_NAMES
							__a					:   Tuple									=       PRETRAINED_INIT_CONFIGURATION
							__a					:   Dict									=       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							__a					:   Optional[int]									=       PRETRAINED_VOCAB_FILES_MAP
							__a					:   Union[str, Any]									=       RESOURCE_FILES_NAMES

							def __init__(							self							:     Union[str, Any]       ,     __magic_name__							:     Dict       ,     __magic_name__							:     int=None       ,     __magic_name__							:     str=False       ,     __magic_name__							:     int="utf8"       ,     __magic_name__							:     Optional[int]="[UNK]"       ,     __magic_name__							:     Dict="[SEP]"       ,     __magic_name__							:     List[Any]="[PAD]"       ,     __magic_name__							:     str="[CLS]"       ,     __magic_name__							:     Optional[int]="[MASK]"       ,     __magic_name__							:     Optional[Dict[str, Any]] = None       ,     **__magic_name__							:     Union[str, Any]       ,     )					->       None:







													"""simple docstring"""
													# Mask token behave like a normal word, i.e. include the space before it and
													# is included in the raw text, there should be a match in a non-normalized sentence.

													UpperCAmelCase_			:      List[Any]     						=  {} if sp_model_kwargs is None else sp_model_kwargs
													super().__init__(
													    do_lower_case=__magic_name__       ,     unk_token=__magic_name__       ,     sep_token=__magic_name__       ,     pad_token=__magic_name__       ,     cls_token=__magic_name__       ,     mask_token=__magic_name__       ,     vocab_file=__magic_name__       ,     encoding=__magic_name__       ,     sp_model_kwargs=self.sp_model_kwargs       ,     **__magic_name__       ,     )
													UpperCAmelCase_			:      Optional[Any]     						=  do_lower_case
													UpperCAmelCase_			:      List[str]     						=  sentencepiece_model_ckpt
													UpperCAmelCase_			:      Tuple     						=  spm.SentencePieceProcessor(**self.sp_model_kwargs   )
													self.sp_model.Load(__magic_name__   )

													# to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning
													if vocab_file is not None:
																			UpperCAmelCase_			:      List[Any]     						=  self.load_vocab(filepath=__magic_name__   )
													else:
																			UpperCAmelCase_			:      str     						=  {self.sp_model.id_to_piece(__magic_name__   ): id for id in range(self.sp_model.get_piece_size()   )}
													UpperCAmelCase_			:      int     						=  {v: k for k, v in self.vocab.items()}

							def     UpperCAmelCase__	(							self							:     List[str]       ,     __magic_name__							:     Any   )					->       Any:







													"""simple docstring"""
													if text is None:
																			return None

													UpperCAmelCase_			:      str     						=  self.tokenize(__magic_name__   )
													UpperCAmelCase_						,       UpperCAmelCase_			:      str     						=  '''''', []

													for i, ch in enumerate(__magic_name__   ):
																			if ch in self.SP_CHAR_MAPPING:
																									UpperCAmelCase_			:      Optional[int]     						=  self.SP_CHAR_MAPPING.get(__magic_name__   )
																			else:
																									UpperCAmelCase_			:      Union[str, Any]     						=  unicodedata.normalize('''NFKC'''       ,     __magic_name__   )
																			if self.is_whitespace(__magic_name__   ):
																									continue
																			normalized_text += ch
																			char_mapping.extend([i] * len(__magic_name__   )   )

													UpperCAmelCase_						,       UpperCAmelCase_						,       UpperCAmelCase_			:      Union[str, Any]     						=  normalized_text, [], 0

													if self.do_lower_case:
																			UpperCAmelCase_			:      Optional[int]     						=  text.lower()

													for token in split_tokens:
																			if token[:1] == "▁":
																									UpperCAmelCase_			:      Tuple     						=  token[1:]
																			UpperCAmelCase_			:      int     						=  text[offset:].index(__magic_name__   ) + offset
																			UpperCAmelCase_			:      Optional[int]     						=  start + len(__magic_name__   )

																			token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1)   )
																			UpperCAmelCase_			:      int     						=  end
													return token_mapping

							@property
							def     UpperCAmelCase__	(							self							:     Any   )					->       Any:







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

							def     UpperCAmelCase__	(							self							:     List[Any]   )					->       int:







													"""simple docstring"""
													return dict(self.vocab       ,     **self.added_tokens_encoder   )

							def __getstate__(							self							:     str   )					->       Any:







													"""simple docstring"""
													UpperCAmelCase_			:      Optional[Any]     						=  self.__dict__.copy()
													UpperCAmelCase_			:      Optional[Any]     						=  None
													return state

							def __setstate__(							self							:     str       ,     __magic_name__							:     Any   )					->       Dict:







													"""simple docstring"""
													UpperCAmelCase_			:      Dict     						=  d

													# for backward compatibility
													if not hasattr(self       ,     '''sp_model_kwargs'''   ):
																			UpperCAmelCase_			:      int     						=  {}

													UpperCAmelCase_			:      List[Any]     						=  spm.SentencePieceProcessor(**self.sp_model_kwargs   )
													self.sp_model.Load(self.sentencepiece_model_ckpt   )

							def     UpperCAmelCase__	(							self							:     Optional[int]       ,     __magic_name__							:     Any   )					->       List[str]:







													"""simple docstring"""
													return "".join((self.SP_CHAR_MAPPING.get(__magic_name__       ,     __magic_name__   ) for c in text)   )

							def     UpperCAmelCase__	(							self							:     List[str]       ,     __magic_name__							:     Tuple       ,     __magic_name__							:     Any=False       ,     __magic_name__							:     List[str]=64       ,     __magic_name__							:     List[str]=0.1   )					->       List[str]:







													"""simple docstring"""

													if self.sp_model_kwargs.get('''enable_sampling'''   ) is True:
																			UpperCAmelCase_			:      Dict     						=  True
													if self.sp_model_kwargs.get('''alpha'''   ) is not None:
																			UpperCAmelCase_			:      Union[str, Any]     						=  self.sp_model_kwargs.get('''alpha'''   )
													if self.sp_model_kwargs.get('''nbest_size'''   ) is not None:
																			UpperCAmelCase_			:      Any     						=  self.sp_model_kwargs.get('''nbest_size'''   )

													if not enable_sampling:
																			UpperCAmelCase_			:      Dict     						=  self.sp_model.EncodeAsPieces(__magic_name__   )
													else:
																			UpperCAmelCase_			:      Dict     						=  self.sp_model.SampleEncodeAsPieces(__magic_name__       ,     __magic_name__       ,     __magic_name__   )
													UpperCAmelCase_			:      List[Any]     						=  []
													for pi, piece in enumerate(__magic_name__   ):
																			if piece == SPIECE_UNDERLINE:
																									if not pieces[pi + 1].startswith(__magic_name__   ) and pi != 0:
																															new_pieces.append(__magic_name__   )
																															continue
																									else:
																															continue
																			UpperCAmelCase_			:      List[str]     						=  0
																			for i, chunk in enumerate(__magic_name__   ):
																									if chunk == SPIECE_UNDERLINE:
																															continue
																									if self.is_ch_char(__magic_name__   ) or self.is_punct(__magic_name__   ):
																															if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
																																					new_pieces.append(piece[lst_i:i]   )
																															new_pieces.append(__magic_name__   )
																															UpperCAmelCase_			:      List[Any]     						=  i + 1
																									elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit():
																															if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
																																					new_pieces.append(piece[lst_i:i]   )
																															UpperCAmelCase_			:      List[str]     						=  i
																									elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit():
																															if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
																																					new_pieces.append(piece[lst_i:i]   )
																															UpperCAmelCase_			:      str     						=  i
																			if len(__magic_name__   ) > lst_i:
																									new_pieces.append(piece[lst_i:]   )
													return new_pieces

							def     UpperCAmelCase__	(							self							:     List[Any]       ,     __magic_name__							:     Optional[int]   )					->       List[str]:







													"""simple docstring"""
													UpperCAmelCase_			:      Optional[Any]     						=  ''''''.join(__magic_name__   ).replace(__magic_name__       ,     ''' '''   ).strip()
													return out_string

							def     UpperCAmelCase__	(							self							:     List[Any]       ,     __magic_name__							:     Union[str, Any]   )					->       List[str]:







													"""simple docstring"""
													UpperCAmelCase_			:      str     						=  self.convert_ids_to_tokens(__magic_name__   )
													UpperCAmelCase_			:      Optional[Any]     						=  ''''''.join(__magic_name__   ).replace(__magic_name__       ,     ''' '''   ).strip()
													return out_string

							def     UpperCAmelCase__	(							self							:     str       ,     __magic_name__							:     Optional[Any]   )					->       List[Any]:







													"""simple docstring"""
													return self.vocab.get(__magic_name__       ,     self.vocab.get(self.unk_token   )   )

							def     UpperCAmelCase__	(							self							:     Tuple       ,     __magic_name__							:     Union[str, Any]   )					->       Union[str, Any]:







													"""simple docstring"""
													return self.reverse_vocab.get(__magic_name__       ,     self.unk_token   )

							def     UpperCAmelCase__	(							self							:     Tuple       ,     __magic_name__							:     Any       ,     __magic_name__							:     Union[str, Any]=None   )					->       Any:







													"""simple docstring"""
													if token_ids_a is None:
																			return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
													UpperCAmelCase_			:      Union[str, Any]     						=  [self.cls_token_id]
													UpperCAmelCase_			:      List[Any]     						=  [self.sep_token_id]
													return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep

							def     UpperCAmelCase__	(							self							:     Any       ,     __magic_name__							:     Optional[Any]       ,     __magic_name__							:     List[str]=None   )					->       int:







													"""simple docstring"""
													if offset_mapping_a is None:
																			return [(0, 0)] + offset_mapping_a + [(0, 0)]

													return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)]

							def     UpperCAmelCase__	(							self							:     Dict       ,     __magic_name__							:     Optional[Any]       ,     __magic_name__							:     List[str]=None       ,     __magic_name__							:     Optional[Any]=False   )					->       Optional[int]:







													"""simple docstring"""

													if already_has_special_tokens:
																			if token_ids_a is not None:
																									raise ValueError(
																									    '''You should not supply a second sequence if the provided sequence of '''
																									    '''ids is already formatted with special tokens for the model.'''   )
																			return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]

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

							def     UpperCAmelCase__	(							self							:     List[str]       ,     __magic_name__							:     List[int]       ,     __magic_name__							:     Optional[List[int]] = None   )					->       List[int]:







													"""simple docstring"""
													# called when `add_special_tokens` is True, so align with `build_inputs_with_special_tokens` method
													if token_ids_a is None:
																			# [CLS] X [SEP]
																			return (len(__magic_name__   ) + 2) * [0]

													# [CLS] A [SEP] [SEP] B [SEP]
													return [0] * (len(__magic_name__   ) + 1) + [1] * (len(__magic_name__   ) + 3)

							def     UpperCAmelCase__	(							self							:     Dict       ,     __magic_name__							:     str   )					->       Tuple:







													"""simple docstring"""
													if "\u4e00" <= char <= "\u9fff":
																			return True
													return False

							def     UpperCAmelCase__	(							self							:     int       ,     __magic_name__							:     Optional[int]   )					->       str:







													"""simple docstring"""
													if ("a" <= char <= "z") or ("A" <= char <= "Z"):
																			return True
													return False

							def     UpperCAmelCase__	(							self							:     int       ,     __magic_name__							:     Optional[Any]   )					->       Dict:







													"""simple docstring"""
													if char in ",;:.?!~，；：。？！《》【】":
																			return True
													return False

							def     UpperCAmelCase__	(							self							:     Tuple       ,     __magic_name__							:     Any   )					->       Union[str, Any]:







													"""simple docstring"""
													if char == " " or char == "\t" or char == "\n" or char == "\r":
																			return True
													if len(__magic_name__   ) == 1:
																			UpperCAmelCase_			:      Optional[Any]     						=  unicodedata.category(__magic_name__   )
																			if cat == "Zs":
																									return True
													return False

							def     UpperCAmelCase__	(							self							:     Union[str, Any]       ,     __magic_name__							:     Tuple   )					->       Any:







													"""simple docstring"""
													UpperCAmelCase_			:      Optional[Any]     						=  {}
													with io.open(__magic_name__       ,     '''r'''       ,     encoding='''utf-8'''   ) as f:
																			for index, line in enumerate(__magic_name__   ):
																									UpperCAmelCase_			:      List[Any]     						=  line.rstrip('''\n'''   )
																									UpperCAmelCase_			:      Dict     						=  int(__magic_name__   )

													return token_to_idx



							def     UpperCAmelCase__	(							self							:     Dict       ,     __magic_name__							:     str       ,     __magic_name__							:     Optional[str] = None   )					->       Tuple[str]:







													"""simple docstring"""
													UpperCAmelCase_			:      Union[str, Any]     						=  0
													if os.path.isdir(__magic_name__   ):
																			UpperCAmelCase_			:      Any     						=  os.path.join(
																			    __magic_name__       ,     (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']   )
													else:
																			UpperCAmelCase_			:      List[str]     						=  (filename_prefix + '''-''' if filename_prefix else '''''') + save_directory
													with open(__magic_name__       ,     '''w'''       ,     encoding='''utf-8'''   ) as writer:
																			for token, token_index in sorted(self.vocab.items()       ,     key=lambda __magic_name__   : kv[1]   ):
																									if index != token_index:
																															logger.warning(
																															    F"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."""
																															    ''' Please check that the vocabulary is not corrupted!'''   )
																															UpperCAmelCase_			:      Dict     						=  token_index
																									writer.write(token + '''\n'''   )
																									index += 1

													UpperCAmelCase_			:      Union[str, Any]     						=  os.path.join(__magic_name__       ,     '''sentencepiece.bpe.model'''   )
													with open(__magic_name__       ,     '''wb'''   ) as fi:
																			UpperCAmelCase_			:      Optional[int]     						=  self.sp_model.serialized_model_proto()
																			fi.write(__magic_name__   )

													return (vocab_file,)





