





"""simple docstring"""


import os
import re
import warnings
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer


if TYPE_CHECKING:
		from ...tokenization_utils_base import TextInput
from ...utils import logging


a_       							=    logging.get_logger(__name__)

a_       							=    {"vocab_file": "spiece.model"}

a_       							=    {
    "vocab_file": {
        "t5-small": "https://huggingface.co/t5-small/resolve/main/spiece.model",
        "t5-base": "https://huggingface.co/t5-base/resolve/main/spiece.model",
        "t5-large": "https://huggingface.co/t5-large/resolve/main/spiece.model",
        "t5-3b": "https://huggingface.co/t5-3b/resolve/main/spiece.model",
        "t5-11b": "https://huggingface.co/t5-11b/resolve/main/spiece.model",
    }
}


# TODO(PVP) - this should be removed in Transformers v5
a_       							=    {
    "t5-small": 5_12,
    "t5-base": 5_12,
    "t5-large": 5_12,
    "t5-3b": 5_12,
    "t5-11b": 5_12,
}

a_       							=    "▁"
class snake_case      (  _UpperCamelCase):
		__UpperCamelCase           =			VOCAB_FILES_NAMES
		__UpperCamelCase           =			PRETRAINED_VOCAB_FILES_MAP
		__UpperCamelCase           =			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
		__UpperCamelCase           =			['input_ids', 'attention_mask']







		def __init__(					self      :       List[str]    ,   a__      :       Optional[int]    ,   a__      :       Union[str, Any]="</s>"    ,   a__      :       Union[str, Any]="<unk>"    ,   a__      :       str="<pad>"    ,   a__      :       Optional[int]=1_00    ,   a__      :       List[Any]=None    ,   a__      :       Optional[Dict[str, Any]] = None    ,   a__      :       Any=True    ,   **a__      :       Optional[int]    ,   )       ->						None:





						'''simple docstring'''







						if extra_ids > 0 and additional_special_tokens is None:
										_A					  =			[F"""<extra_id_{i}>""" for i in range(a__		)]
						elif extra_ids > 0 and additional_special_tokens is not None:
										# Check that we have the right number of extra_id special tokens
										_A					  =			len(set(filter(lambda a__		: bool("extra_id" in str(a__		)		)    ,   a__		)		)		)
										if extra_tokens != extra_ids:
														raise ValueError(
														    F"""Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"""
														    " provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids"
														    " tokens"		)
						if legacy:
										logger.warning_once(
										    F"""You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to"""
										    " read the related pull request available at https://github.com/huggingface/transformers/pull/24565"		)

						_A					  =			legacy
						_A					  =			{} if sp_model_kwargs is None else sp_model_kwargs

						super().__init__(
						    eos_token=a__    ,   unk_token=a__    ,   pad_token=a__    ,   extra_ids=a__    ,   additional_special_tokens=a__    ,   sp_model_kwargs=self.sp_model_kwargs    ,   legacy=a__    ,   **a__    ,   )

						_A					  =			vocab_file
						_A					  =			extra_ids

						_A					  =			spm.SentencePieceProcessor(**self.sp_model_kwargs		)
						self.sp_model.Load(a__		)







		@staticmethod
		def  a_ (					a__      :       List[str]    ,   a__      :       Optional[int]    ,   a__      :       Tuple		)       ->						Tuple:





						'''simple docstring'''







						if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes:
										_A					  =			TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path]
										if init_max_model_length is not None and init_max_model_length != max_model_length:
														return init_max_model_length
										elif init_max_model_length is None:
														warnings.warn(
														    "This tokenizer was incorrectly instantiated with a model max length of"
														    F""" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this"""
														    " behavior is kept to avoid breaking backwards compatibility when padding/encoding with"
														    " `truncation is True`.\n- Be aware that you SHOULD NOT rely on"
														    F""" {pretrained_model_name_or_path} automatically truncating your input to"""
														    F""" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences"""
														    F""" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with"""
														    " `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please"
														    " instantiate this tokenizer with `model_max_length` set to your preferred value."    ,   a__    ,   )

						return max_model_length







		@property
		def  a_ (					self      :       List[Any]		)       ->						Dict:





						'''simple docstring'''







						return self.sp_model.get_piece_size() + self._extra_ids







		def  a_ (					self      :       Dict		)       ->						Optional[Any]:





						'''simple docstring'''







						_A					  =			{self.convert_ids_to_tokens(a__		): i for i in range(self.vocab_size		)}
						vocab.update(self.added_tokens_encoder		)
						return vocab







		def  a_ (					self      :       Optional[Any]    ,   a__      :       List[int]    ,   a__      :       Optional[List[int]] = None    ,   a__      :       bool = False		)       ->						List[int]:





						'''simple docstring'''







						if already_has_special_tokens:
										return super().get_special_tokens_mask(
										    token_ids_a=a__    ,   token_ids_a=a__    ,   already_has_special_tokens=a__		)

						# normal case: some special tokens
						if token_ids_a is None:
										return ([0] * len(a__		)) + [1]
						return ([0] * len(a__		)) + [1] + ([0] * len(a__		)) + [1]







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





						'''simple docstring'''







						return list(
						    set(filter(lambda a__		: bool(re.search(r"<extra_id_\d+>"    ,   a__		)		) is not None    ,   self.additional_special_tokens		)		)		)







		def  a_ (					self      :       str		)       ->						List[Any]:





						'''simple docstring'''







						return [self._convert_token_to_id(a__		) for token in self.get_sentinel_tokens()]







		def  a_ (					self      :       List[Any]    ,   a__      :       List[int]		)       ->						List[int]:





						'''simple docstring'''







						if len(a__		) > 0 and token_ids[-1] == self.eos_token_id:
										warnings.warn(
										    F"""This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated"""
										    " eos tokens being added."		)
										return token_ids
						else:
										return token_ids + [self.eos_token_id]







		def  a_ (					self      :       int    ,   a__      :       List[int]    ,   a__      :       Optional[List[int]] = None		)       ->						List[int]:





						'''simple docstring'''







						_A					  =			[self.eos_token_id]

						if token_ids_a is None:
										return len(token_ids_a + eos		) * [0]
						return len(token_ids_a + eos + token_ids_a + eos		) * [0]







		def  a_ (					self      :       Union[str, Any]    ,   a__      :       List[int]    ,   a__      :       Optional[List[int]] = None		)       ->						List[int]:





						'''simple docstring'''







						_A					  =			self._add_eos_if_not_present(a__		)
						if token_ids_a is None:
										return token_ids_a
						else:
										_A					  =			self._add_eos_if_not_present(a__		)
										return token_ids_a + token_ids_a







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





						'''simple docstring'''







						_A					  =			self.__dict__.copy()
						_A					  =			None
						return state







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





						'''simple docstring'''







						_A					  =			d

						# for backward compatibility
						if not hasattr(self    ,   "sp_model_kwargs"		):
										_A					  =			{}

						_A					  =			spm.SentencePieceProcessor(**self.sp_model_kwargs		)
						self.sp_model.Load(self.vocab_file		)







		def  a_ (					self      :       int    ,   a__      :       "TextInput"    ,   **a__      :       List[str]		)       ->						List[str]:





						'''simple docstring'''







						if not self.legacy:
										_A					  =			SPIECE_UNDERLINE + text.replace(a__    ,   " "		)
						return super().tokenize(a__    ,   **a__		)







		def  a_ (					self      :       str    ,   a__      :       Dict    ,   **a__      :       Optional[int]		)       ->						Any:





						'''simple docstring'''







						if not self.legacy:
										_A					  =			text.startswith(a__		)
										if is_first:
														_A					  =			text[1:]

						_A					  =			self.sp_model.encode(a__    ,   out_type=a__		)

						if not self.legacy and not is_first and not text.startswith(" "		) and tokens[0].startswith(a__		):
										_A					  =			([tokens[0][1:]] if len(tokens[0]		) > 1 else []) + tokens[1:]
						return tokens







		def  a_ (					self      :       int    ,   a__      :       List[Any]		)       ->						List[str]:





						'''simple docstring'''







						if token.startswith("<extra_id_"		):
										_A					  =			re.match(r"<extra_id_(\d+)>"    ,   a__		)
										_A					  =			int(match.group(1		)		)
										return self.vocab_size - num - 1
						return self.sp_model.piece_to_id(a__		)







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





						'''simple docstring'''







						if index < self.sp_model.get_piece_size():
										_A					  =			self.sp_model.IdToPiece(a__		)
						else:
										_A					  =			F"""<extra_id_{self.vocab_size - 1 - index}>"""
						return token







		def  a_ (					self      :       Optional[int]    ,   a__      :       Tuple		)       ->						List[str]:





						'''simple docstring'''







						_A					  =			[]
						_A					  =			""
						_A					  =			False
						for token in tokens:
										# make sure that special tokens are not decoded using sentencepiece model
										if token in self.all_special_tokens:
														if not prev_is_special:
																		out_string += " "
														out_string += self.sp_model.decode(a__		) + token
														_A					  =			True
														_A					  =			[]
										else:
														current_sub_tokens.append(a__		)
														_A					  =			False
						out_string += self.sp_model.decode(a__		)
						return out_string.strip()







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





						'''simple docstring'''







						if not os.path.isdir(a__		):
										logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""		)
										return
						_A					  =			os.path.join(
						    a__    ,   (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]		)

						if os.path.abspath(self.vocab_file		) != os.path.abspath(a__		) and os.path.isfile(self.vocab_file		):
										copyfile(self.vocab_file    ,   a__		)
						elif not os.path.isfile(self.vocab_file		):
										with open(a__    ,   "wb"		) as fi:
														_A					  =			self.sp_model.serialized_model_proto()
														fi.write(a__		)

						return (out_vocab_file,)



"""simple docstring"""


import gc
import random
import unittest

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

from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow

from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()
class snake_case      (  _UpperCamelCase     ,				_UpperCamelCase     ,				_UpperCamelCase     ,				unittest.TestCase):
		__UpperCamelCase           =			StableDiffusionInpaintPipeline
		__UpperCamelCase           =			TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
		__UpperCamelCase           =			TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
		__UpperCamelCase           =			frozenset(
		    [])  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
		__UpperCamelCase           =			frozenset([])







		def  a_ (					self      :       Dict		)       ->						Optional[int]:





						'''simple docstring'''







						torch.manual_seed(0		)
						_A					  =			UNetaDConditionModel(
						    block_out_channels=(32, 64)    ,   layers_per_block=2    ,   sample_size=32    ,   in_channels=9    ,   out_channels=4    ,   down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")    ,   up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")    ,   cross_attention_dim=32    ,   attention_head_dim=(2, 4)    ,   use_linear_projection=a__    ,   )
						_A					  =			PNDMScheduler(skip_prk_steps=a__		)
						torch.manual_seed(0		)
						_A					  =			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    ,   sample_size=1_28    ,   )
						torch.manual_seed(0		)
						_A					  =			CLIPTextConfig(
						    bos_token_id=0    ,   eos_token_id=2    ,   hidden_size=32    ,   intermediate_size=37    ,   layer_norm_eps=1E-0_5    ,   num_attention_heads=4    ,   num_hidden_layers=5    ,   pad_token_id=1    ,   vocab_size=10_00    ,   hidden_act="gelu"    ,   projection_dim=5_12    ,   )
						_A					  =			CLIPTextModel(a__		)
						_A					  =			CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"		)

						_A					  =			{
						    "unet": unet,
						    "scheduler": scheduler,
						    "vae": vae,
						    "text_encoder": text_encoder,
						    "tokenizer": tokenizer,
						    "safety_checker": None,
						    "feature_extractor": None,
						}
						return components







		def  a_ (					self      :       Optional[Any]    ,   a__      :       List[str]    ,   a__      :       Tuple=0		)       ->						int:





						'''simple docstring'''







						_A					  =			floats_tensor((1, 3, 32, 32)    ,   rng=random.Random(a__		)		).to(a__		)
						_A					  =			image.cpu().permute(0    ,   2    ,   3    ,   1		)[0]
						_A					  =			Image.fromarray(np.uinta(a__		)		).convert("RGB"		).resize((64, 64)		)
						_A					  =			Image.fromarray(np.uinta(image + 4		)		).convert("RGB"		).resize((64, 64)		)
						if str(a__		).startswith("mps"		):
										_A					  =			torch.manual_seed(a__		)
						else:
										_A					  =			torch.Generator(device=a__		).manual_seed(a__		)
						_A					  =			{
						    "prompt": "A painting of a squirrel eating a burger",
						    "image": init_image,
						    "mask_image": mask_image,
						    "generator": generator,
						    "num_inference_steps": 2,
						    "guidance_scale": 6.0,
						    "output_type": "numpy",
						}
						return inputs







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





						'''simple docstring'''







						_A					  =			"cpu"  # ensure determinism for the device-dependent torch.Generator
						_A					  =			self.get_dummy_components()
						_A					  =			StableDiffusionInpaintPipeline(**a__		)
						_A					  =			sd_pipe.to(a__		)
						sd_pipe.set_progress_bar_config(disable=a__		)

						_A					  =			self.get_dummy_inputs(a__		)
						_A					  =			sd_pipe(**a__		).images
						_A					  =			image[0, -3:, -3:, -1]

						assert image.shape == (1, 64, 64, 3)
						_A					  =			np.array([0.4_7_2_7, 0.5_7_3_5, 0.3_9_4_1, 0.5_4_4_6, 0.5_9_2_6, 0.4_3_9_4, 0.5_0_6_2, 0.4_6_5_4, 0.4_4_7_6]		)

						assert np.abs(image_slice.flatten() - expected_slice		).max() < 1E-2







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





						'''simple docstring'''







						super().test_inference_batch_single_identical(expected_max_diff=3E-3		)





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







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





						'''simple docstring'''







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







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





						'''simple docstring'''







						_A					  =			load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
						    "/sd2-inpaint/init_image.png"		)
						_A					  =			load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png"		)
						_A					  =			load_numpy(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint"
						    "/yellow_cat_sitting_on_a_park_bench.npy"		)

						_A					  =			"stabilityai/stable-diffusion-2-inpainting"
						_A					  =			StableDiffusionInpaintPipeline.from_pretrained(a__    ,   safety_checker=a__		)
						pipe.to(a__		)
						pipe.set_progress_bar_config(disable=a__		)
						pipe.enable_attention_slicing()

						_A					  =			"Face of a yellow cat, high resolution, sitting on a park bench"

						_A					  =			torch.manual_seed(0		)
						_A					  =			pipe(
						    prompt=a__    ,   image=a__    ,   mask_image=a__    ,   generator=a__    ,   output_type="np"    ,   )
						_A					  =			output.images[0]

						assert image.shape == (5_12, 5_12, 3)
						assert np.abs(expected_image - image		).max() < 9E-3







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





						'''simple docstring'''







						_A					  =			load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
						    "/sd2-inpaint/init_image.png"		)
						_A					  =			load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png"		)
						_A					  =			load_numpy(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint"
						    "/yellow_cat_sitting_on_a_park_bench_fp16.npy"		)

						_A					  =			"stabilityai/stable-diffusion-2-inpainting"
						_A					  =			StableDiffusionInpaintPipeline.from_pretrained(
						    a__    ,   torch_dtype=torch.floataa    ,   safety_checker=a__    ,   )
						pipe.to(a__		)
						pipe.set_progress_bar_config(disable=a__		)
						pipe.enable_attention_slicing()

						_A					  =			"Face of a yellow cat, high resolution, sitting on a park bench"

						_A					  =			torch.manual_seed(0		)
						_A					  =			pipe(
						    prompt=a__    ,   image=a__    ,   mask_image=a__    ,   generator=a__    ,   output_type="np"    ,   )
						_A					  =			output.images[0]

						assert image.shape == (5_12, 5_12, 3)
						assert np.abs(expected_image - image		).max() < 5E-1







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





						'''simple docstring'''







						torch.cuda.empty_cache()
						torch.cuda.reset_max_memory_allocated()
						torch.cuda.reset_peak_memory_stats()

						_A					  =			load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
						    "/sd2-inpaint/init_image.png"		)
						_A					  =			load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png"		)

						_A					  =			"stabilityai/stable-diffusion-2-inpainting"
						_A					  =			PNDMScheduler.from_pretrained(a__    ,   subfolder="scheduler"		)
						_A					  =			StableDiffusionInpaintPipeline.from_pretrained(
						    a__    ,   safety_checker=a__    ,   scheduler=a__    ,   torch_dtype=torch.floataa    ,   )
						pipe.to(a__		)
						pipe.set_progress_bar_config(disable=a__		)
						pipe.enable_attention_slicing(1		)
						pipe.enable_sequential_cpu_offload()

						_A					  =			"Face of a yellow cat, high resolution, sitting on a park bench"

						_A					  =			torch.manual_seed(0		)
						_A					  =			pipe(
						    prompt=a__    ,   image=a__    ,   mask_image=a__    ,   generator=a__    ,   num_inference_steps=2    ,   output_type="np"    ,   )

						_A					  =			torch.cuda.max_memory_allocated()
						# make sure that less than 2.65 GB is allocated
						assert mem_bytes < 2.6_5 * 10**9