



'''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 						lowerCamelCase_				(       snake_case_     ,					snake_case_     ,					snake_case_     ,					unittest.TestCase      ):
						_lowerCAmelCase  : str						  =					StableDiffusionInpaintPipeline
						_lowerCAmelCase  : str						  =					TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
						_lowerCAmelCase  : Union[str, Any]						  =					TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
						_lowerCAmelCase  : Optional[Any]						  =					frozenset(
						    []      )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
						_lowerCAmelCase  : int						  =					frozenset([]      )







						def        __lowercase     (	self :   Optional[int]					):

													"""simple docstring"""
													torch.manual_seed(0					)
													SCREAMING_SNAKE_CASE       :   int         =      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=lowerCAmelCase__					,     )
													SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      PNDMScheduler(skip_prk_steps=lowerCAmelCase__					)
													torch.manual_seed(0					)
													SCREAMING_SNAKE_CASE       :   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					,     sample_size=1_28					,     )
													torch.manual_seed(0					)
													SCREAMING_SNAKE_CASE       :   int         =      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					,     hidden_act='''gelu'''					,     projection_dim=5_12					,     )
													SCREAMING_SNAKE_CASE       :   Any         =      CLIPTextModel(lowerCAmelCase__					)
													SCREAMING_SNAKE_CASE       :   List[str]         =      CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''					)

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







						def        __lowercase     (	self :   List[str]					,     lowerCAmelCase__ :   Optional[Any]					,     lowerCAmelCase__ :   Union[str, Any]=0					):

													"""simple docstring"""
													# TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched
													SCREAMING_SNAKE_CASE       :   Optional[Any]         =      floats_tensor((1, 3, 32, 32)					,     rng=random.Random(lowerCAmelCase__					)					).to(lowerCAmelCase__					)
													SCREAMING_SNAKE_CASE       :   str         =      image.cpu().permute(0					,     2					,     3					,     1					)[0]
													SCREAMING_SNAKE_CASE       :   List[Any]         =      Image.fromarray(np.uinta(lowerCAmelCase__					)					).convert('''RGB'''					).resize((64, 64)					)
													SCREAMING_SNAKE_CASE       :   int         =      Image.fromarray(np.uinta(image + 4					)					).convert('''RGB'''					).resize((64, 64)					)
													if str(lowerCAmelCase__					).startswith('''mps'''					):
																				SCREAMING_SNAKE_CASE       :   Optional[int]         =      torch.manual_seed(lowerCAmelCase__					)
													else:
																				SCREAMING_SNAKE_CASE       :   List[str]         =      torch.Generator(device=lowerCAmelCase__					).manual_seed(lowerCAmelCase__					)
													SCREAMING_SNAKE_CASE       :   str         =      {
													    '''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        __lowercase     (	self :   Dict					):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE       :   List[str]         =      '''cpu'''  # ensure determinism for the device-dependent torch.Generator
													SCREAMING_SNAKE_CASE       :   Tuple         =      self.get_dummy_components()
													SCREAMING_SNAKE_CASE       :   Tuple         =      StableDiffusionInpaintPipeline(**lowerCAmelCase__					)
													SCREAMING_SNAKE_CASE       :   Tuple         =      sd_pipe.to(lowerCAmelCase__					)
													sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__					)

													SCREAMING_SNAKE_CASE       :   Optional[int]         =      self.get_dummy_inputs(lowerCAmelCase__					)
													SCREAMING_SNAKE_CASE       :   List[str]         =      sd_pipe(**lowerCAmelCase__					).images
													SCREAMING_SNAKE_CASE       :   int         =      image[0, -3:, -3:, -1]

													assert image.shape == (1, 64, 64, 3)
													SCREAMING_SNAKE_CASE       :   List[str]         =      np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476]					)

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







						def        __lowercase     (	self :   List[str]					):

													"""simple docstring"""
													super().test_inference_batch_single_identical(expected_max_diff=3e-3					)


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







						def        __lowercase     (	self :   List[str]					):

													"""simple docstring"""
													# clean up the VRAM after each test
													super().tearDown()
													gc.collect()
													torch.cuda.empty_cache()







						def        __lowercase     (	self :   List[str]					):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      load_image(
													    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
													    '''/sd2-inpaint/init_image.png'''					)
													SCREAMING_SNAKE_CASE       :   List[str]         =      load_image(
													    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png'''					)
													SCREAMING_SNAKE_CASE       :   Optional[int]         =      load_numpy(
													    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint'''
													    '''/yellow_cat_sitting_on_a_park_bench.npy'''					)

													SCREAMING_SNAKE_CASE       :   int         =      '''stabilityai/stable-diffusion-2-inpainting'''
													SCREAMING_SNAKE_CASE       :   List[str]         =      StableDiffusionInpaintPipeline.from_pretrained(lowerCAmelCase__					,     safety_checker=lowerCAmelCase__					)
													pipe.to(lowerCAmelCase__					)
													pipe.set_progress_bar_config(disable=lowerCAmelCase__					)
													pipe.enable_attention_slicing()

													SCREAMING_SNAKE_CASE       :   List[str]         =      '''Face of a yellow cat, high resolution, sitting on a park bench'''

													SCREAMING_SNAKE_CASE       :   List[Any]         =      torch.manual_seed(0					)
													SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      pipe(
													    prompt=lowerCAmelCase__					,     image=lowerCAmelCase__					,     mask_image=lowerCAmelCase__					,     generator=lowerCAmelCase__					,     output_type='''np'''					,     )
													SCREAMING_SNAKE_CASE       :   List[str]         =      output.images[0]

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







						def        __lowercase     (	self :   Dict					):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE       :   Dict         =      load_image(
													    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
													    '''/sd2-inpaint/init_image.png'''					)
													SCREAMING_SNAKE_CASE       :   List[str]         =      load_image(
													    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png'''					)
													SCREAMING_SNAKE_CASE       :   List[Any]         =      load_numpy(
													    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint'''
													    '''/yellow_cat_sitting_on_a_park_bench_fp16.npy'''					)

													SCREAMING_SNAKE_CASE       :   Optional[Any]         =      '''stabilityai/stable-diffusion-2-inpainting'''
													SCREAMING_SNAKE_CASE       :   List[str]         =      StableDiffusionInpaintPipeline.from_pretrained(
													    lowerCAmelCase__					,     torch_dtype=torch.floataa					,     safety_checker=lowerCAmelCase__					,     )
													pipe.to(lowerCAmelCase__					)
													pipe.set_progress_bar_config(disable=lowerCAmelCase__					)
													pipe.enable_attention_slicing()

													SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      '''Face of a yellow cat, high resolution, sitting on a park bench'''

													SCREAMING_SNAKE_CASE       :   int         =      torch.manual_seed(0					)
													SCREAMING_SNAKE_CASE       :   Optional[int]         =      pipe(
													    prompt=lowerCAmelCase__					,     image=lowerCAmelCase__					,     mask_image=lowerCAmelCase__					,     generator=lowerCAmelCase__					,     output_type='''np'''					,     )
													SCREAMING_SNAKE_CASE       :   Optional[Any]         =      output.images[0]

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







						def        __lowercase     (	self :   List[Any]					):

													"""simple docstring"""
													torch.cuda.empty_cache()
													torch.cuda.reset_max_memory_allocated()
													torch.cuda.reset_peak_memory_stats()

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

													SCREAMING_SNAKE_CASE       :   int         =      '''stabilityai/stable-diffusion-2-inpainting'''
													SCREAMING_SNAKE_CASE       :   str         =      PNDMScheduler.from_pretrained(lowerCAmelCase__					,     subfolder='''scheduler'''					)
													SCREAMING_SNAKE_CASE       :   Optional[int]         =      StableDiffusionInpaintPipeline.from_pretrained(
													    lowerCAmelCase__					,     safety_checker=lowerCAmelCase__					,     scheduler=lowerCAmelCase__					,     torch_dtype=torch.floataa					,     )
													pipe.to(lowerCAmelCase__					)
													pipe.set_progress_bar_config(disable=lowerCAmelCase__					)
													pipe.enable_attention_slicing(1					)
													pipe.enable_sequential_cpu_offload()

													SCREAMING_SNAKE_CASE       :   int         =      '''Face of a yellow cat, high resolution, sitting on a park bench'''

													SCREAMING_SNAKE_CASE       :   Tuple         =      torch.manual_seed(0					)
													SCREAMING_SNAKE_CASE       :   int         =      pipe(
													    prompt=lowerCAmelCase__					,     image=lowerCAmelCase__					,     mask_image=lowerCAmelCase__					,     generator=lowerCAmelCase__					,     num_inference_steps=2					,     output_type='''np'''					,     )

													SCREAMING_SNAKE_CASE       :   List[str]         =      torch.cuda.max_memory_allocated()
													# make sure that less than 2.65 GB is allocated
													assert mem_bytes < 2.65 * 10**9









'''simple docstring'''



import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel

from ...utils import logging


lowerCAmelCase_  :							int             =    logging.get_logger(__name__)
def        UpperCAmelCase (    A	:					List[Any]       ,		A	:					Optional[int]					):
							SCREAMING_SNAKE_CASE       :   Any         =      nn.functional.normalize(A					)
							SCREAMING_SNAKE_CASE       :   List[str]         =      nn.functional.normalize(A					)
							return torch.mm(A       ,		normalized_text_embeds.t()					)






class 						lowerCamelCase_				(       snake_case_      ):
						_lowerCAmelCase  : Optional[Any]						  =					CLIPConfig

						_lowerCAmelCase  : List[str]						  =					['CLIPEncoderLayer']







						def __init__(	self :   int					,     lowerCAmelCase__ :   CLIPConfig					):

													"""simple docstring"""
													super().__init__(lowerCAmelCase__					)

													SCREAMING_SNAKE_CASE       :   Any         =      CLIPVisionModel(config.vision_config					)
													SCREAMING_SNAKE_CASE       :   List[str]         =      nn.Linear(config.vision_config.hidden_size					,     config.projection_dim					,     bias=lowerCAmelCase__					)

													SCREAMING_SNAKE_CASE       :   Any         =      nn.Parameter(torch.ones(17					,     config.projection_dim					)					,     requires_grad=lowerCAmelCase__					)
													SCREAMING_SNAKE_CASE       :   int         =      nn.Parameter(torch.ones(3					,     config.projection_dim					)					,     requires_grad=lowerCAmelCase__					)

													SCREAMING_SNAKE_CASE       :   Dict         =      nn.Parameter(torch.ones(17					)					,     requires_grad=lowerCAmelCase__					)
													SCREAMING_SNAKE_CASE       :   List[str]         =      nn.Parameter(torch.ones(3					)					,     requires_grad=lowerCAmelCase__					)







						@torch.no_grad()
						def        __lowercase     (	self :   List[str]					,     lowerCAmelCase__ :   List[str]					,     lowerCAmelCase__ :   Optional[Any]					):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE       :   Any         =      self.vision_model(lowerCAmelCase__					)[1]  # pooled_output
													SCREAMING_SNAKE_CASE       :   Any         =      self.visual_projection(lowerCAmelCase__					)

													# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
													SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      cosine_distance(lowerCAmelCase__					,     self.special_care_embeds					).cpu().float().numpy()
													SCREAMING_SNAKE_CASE       :   List[str]         =      cosine_distance(lowerCAmelCase__					,     self.concept_embeds					).cpu().float().numpy()

													SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      []
													SCREAMING_SNAKE_CASE       :   int         =      image_embeds.shape[0]
													for i in range(lowerCAmelCase__					):
																				SCREAMING_SNAKE_CASE       :   Any         =      {'''special_scores''': {}, '''special_care''': [], '''concept_scores''': {}, '''bad_concepts''': []}

																				# increase this value to create a stronger `nfsw` filter
																				# at the cost of increasing the possibility of filtering benign images
																				SCREAMING_SNAKE_CASE       :   int         =      0.0

																				for concept_idx in range(len(special_cos_dist[0]					)					):
																											SCREAMING_SNAKE_CASE       :   Optional[int]         =      special_cos_dist[i][concept_idx]
																											SCREAMING_SNAKE_CASE       :   int         =      self.special_care_embeds_weights[concept_idx].item()
																											SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      round(concept_cos - concept_threshold + adjustment					,     3					)
																											if result_img["special_scores"][concept_idx] > 0:
																																		result_img["special_care"].append({concept_idx, result_img['''special_scores'''][concept_idx]}					)
																																		SCREAMING_SNAKE_CASE       :   Tuple         =      0.01

																				for concept_idx in range(len(cos_dist[0]					)					):
																											SCREAMING_SNAKE_CASE       :   Optional[Any]         =      cos_dist[i][concept_idx]
																											SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      self.concept_embeds_weights[concept_idx].item()
																											SCREAMING_SNAKE_CASE       :   Dict         =      round(concept_cos - concept_threshold + adjustment					,     3					)
																											if result_img["concept_scores"][concept_idx] > 0:
																																		result_img["bad_concepts"].append(lowerCAmelCase__					)

																				result.append(lowerCAmelCase__					)

													SCREAMING_SNAKE_CASE       :   Dict         =      [len(res['''bad_concepts''']					) > 0 for res in result]

													return images, has_nsfw_concepts







						@torch.no_grad()
						def        __lowercase     (	self :   List[str]					,     lowerCAmelCase__ :   torch.FloatTensor					,     lowerCAmelCase__ :   torch.FloatTensor					):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      self.vision_model(lowerCAmelCase__					)[1]  # pooled_output
													SCREAMING_SNAKE_CASE       :   List[Any]         =      self.visual_projection(lowerCAmelCase__					)

													SCREAMING_SNAKE_CASE       :   List[str]         =      cosine_distance(lowerCAmelCase__					,     self.special_care_embeds					)
													SCREAMING_SNAKE_CASE       :   List[str]         =      cosine_distance(lowerCAmelCase__					,     self.concept_embeds					)

													# increase this value to create a stronger `nsfw` filter
													# at the cost of increasing the possibility of filtering benign images
													SCREAMING_SNAKE_CASE       :   Optional[int]         =      0.0

													SCREAMING_SNAKE_CASE       :   Any         =      special_cos_dist - self.special_care_embeds_weights + adjustment
													# special_scores = special_scores.round(decimals=3)
													SCREAMING_SNAKE_CASE       :   List[Any]         =      torch.any(special_scores > 0					,     dim=1					)
													SCREAMING_SNAKE_CASE       :   Dict         =      special_care * 0.01
													SCREAMING_SNAKE_CASE       :   List[str]         =      special_adjustment.unsqueeze(1					).expand(-1					,     cos_dist.shape[1]					)

													SCREAMING_SNAKE_CASE       :   Optional[int]         =      (cos_dist - self.concept_embeds_weights) + special_adjustment
													# concept_scores = concept_scores.round(decimals=3)
													SCREAMING_SNAKE_CASE       :   Any         =      torch.any(concept_scores > 0					,     dim=1					)

													return images, has_nsfw_concepts




