




'''simple docstring'''


import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()

class       A   (		unittest.TestCase   ):







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


														"""simple docstring"""


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







							@property
							def        __lowerCAmelCase      (  self	:  int )      ->							Tuple:


														"""simple docstring"""


														_a     					=    1
														_a     					=    3
														_a     					=    (32, 32)

														_a     					=    floats_tensor((batch_size, num_channels) + sizes							,      rng=random.Random(0 ) ).to(lowerCAmelCase_ )
														return image







							@property
							def        __lowerCAmelCase      (  self	:  Optional[Any] )      ->							Optional[Any]:


														"""simple docstring"""


														torch.manual_seed(0 )
														_a     					=    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							,      )
														return model







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


														"""simple docstring"""


														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							,      )
														return model







							@property
							def        __lowerCAmelCase      (  self	:  int )      ->							str:


														"""simple docstring"""


														torch.manual_seed(0 )
														_a     					=    RobertaSeriesConfig(
														    hidden_size=32							,      project_dim=32							,      intermediate_size=37							,      layer_norm_eps=1e-05							,      num_attention_heads=4							,      num_hidden_layers=5							,      pad_token_id=1							,      vocab_size=50_06							,      )
														return RobertaSeriesModelWithTransformation(lowerCAmelCase_ )







							@property
							def        __lowerCAmelCase      (  self	:  List[str] )      ->							Optional[int]:


														"""simple docstring"""


														def extract(*lowerCAmelCase_	:  Any							,      **lowerCAmelCase_	:  Union[str, Any] ):

																					class       A   :







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


																																			"""simple docstring"""


																																			_a     					=    torch.ones([0] )







																												def        __lowerCAmelCase      (  self	:  Tuple							,      lowerCAmelCase_	:  Tuple )      ->							Any:


																																			"""simple docstring"""


																																			self.pixel_values.to(lowerCAmelCase_ )
																																			return self



																					return Out()

														return extract







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


														"""simple docstring"""


														_a     					=    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
														_a     					=    self.dummy_cond_unet
														_a     					=    PNDMScheduler(skip_prk_steps=lowerCAmelCase_ )
														_a     					=    self.dummy_vae
														_a     					=    self.dummy_text_encoder
														_a     					=    XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''' )
														_a     					=    77

														_a     					=    self.dummy_image.to(lowerCAmelCase_ )
														_a     					=    init_image / 2 + 0.5

														# make sure here that pndm scheduler skips prk
														_a     					=    AltDiffusionImgaImgPipeline(
														    unet=lowerCAmelCase_							,      scheduler=lowerCAmelCase_							,      vae=lowerCAmelCase_							,      text_encoder=lowerCAmelCase_							,      tokenizer=lowerCAmelCase_							,      safety_checker=lowerCAmelCase_							,      feature_extractor=self.dummy_extractor							,      )
														_a     					=    VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor							,      do_normalize=lowerCAmelCase_ )
														_a     					=    alt_pipe.to(lowerCAmelCase_ )
														alt_pipe.set_progress_bar_config(disable=lowerCAmelCase_ )

														_a     					=    '''A painting of a squirrel eating a burger'''
														_a     					=    torch.Generator(device=lowerCAmelCase_ ).manual_seed(0 )
														_a     					=    alt_pipe(
														    [prompt]							,      generator=lowerCAmelCase_							,      guidance_scale=6.0							,      num_inference_steps=2							,      output_type='''np'''							,      image=lowerCAmelCase_							,      )

														_a     					=    output.images

														_a     					=    torch.Generator(device=lowerCAmelCase_ ).manual_seed(0 )
														_a     					=    alt_pipe(
														    [prompt]							,      generator=lowerCAmelCase_							,      guidance_scale=6.0							,      num_inference_steps=2							,      output_type='''np'''							,      image=lowerCAmelCase_							,      return_dict=lowerCAmelCase_							,      )[0]

														_a     					=    image[0, -3:, -3:, -1]
														_a     					=    image_from_tuple[0, -3:, -3:, -1]

														assert image.shape == (1, 32, 32, 3)
														_a     					=    np.array([0.4_4_2_7, 0.3_7_3_1, 0.4_2_4_9, 0.4_9_4_1, 0.4_5_4_6, 0.4_1_4_8, 0.4_1_9_3, 0.4_6_6_6, 0.4_4_9_9] )

														assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
														assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 5e-3







							@unittest.skipIf(torch_device != '''cuda'''							,      '''This test requires a GPU''' )
							def        __lowerCAmelCase      (  self	:  int )      ->							int:


														"""simple docstring"""


														_a     					=    self.dummy_cond_unet
														_a     					=    PNDMScheduler(skip_prk_steps=lowerCAmelCase_ )
														_a     					=    self.dummy_vae
														_a     					=    self.dummy_text_encoder
														_a     					=    XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''' )
														_a     					=    77

														_a     					=    self.dummy_image.to(lowerCAmelCase_ )

														# put models in fp16
														_a     					=    unet.half()
														_a     					=    vae.half()
														_a     					=    bert.half()

														# make sure here that pndm scheduler skips prk
														_a     					=    AltDiffusionImgaImgPipeline(
														    unet=lowerCAmelCase_							,      scheduler=lowerCAmelCase_							,      vae=lowerCAmelCase_							,      text_encoder=lowerCAmelCase_							,      tokenizer=lowerCAmelCase_							,      safety_checker=lowerCAmelCase_							,      feature_extractor=self.dummy_extractor							,      )
														_a     					=    VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor							,      do_normalize=lowerCAmelCase_ )
														_a     					=    alt_pipe.to(lowerCAmelCase_ )
														alt_pipe.set_progress_bar_config(disable=lowerCAmelCase_ )

														_a     					=    '''A painting of a squirrel eating a burger'''
														_a     					=    torch.manual_seed(0 )
														_a     					=    alt_pipe(
														    [prompt]							,      generator=lowerCAmelCase_							,      num_inference_steps=2							,      output_type='''np'''							,      image=lowerCAmelCase_							,      ).images

														assert image.shape == (1, 32, 32, 3)







							@unittest.skipIf(torch_device != '''cuda'''							,      '''This test requires a GPU''' )
							def        __lowerCAmelCase      (  self	:  Tuple )      ->							Optional[int]:


														"""simple docstring"""


														_a     					=    load_image(
														    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
														    '''/img2img/sketch-mountains-input.jpg''' )
														# resize to resolution that is divisible by 8 but not 16 or 32
														_a     					=    init_image.resize((7_60, 5_04) )

														_a     					=    '''BAAI/AltDiffusion'''
														_a     					=    AltDiffusionImgaImgPipeline.from_pretrained(
														    lowerCAmelCase_							,      safety_checker=lowerCAmelCase_							,      )
														pipe.to(lowerCAmelCase_ )
														pipe.set_progress_bar_config(disable=lowerCAmelCase_ )
														pipe.enable_attention_slicing()

														_a     					=    '''A fantasy landscape, trending on artstation'''

														_a     					=    torch.manual_seed(0 )
														_a     					=    pipe(
														    prompt=lowerCAmelCase_							,      image=lowerCAmelCase_							,      strength=0.7_5							,      guidance_scale=7.5							,      generator=lowerCAmelCase_							,      output_type='''np'''							,      )
														_a     					=    output.images[0]

														_a     					=    image[2_55:2_58, 3_83:3_86, -1]

														assert image.shape == (5_04, 7_60, 3)
														_a     					=    np.array([0.9_3_5_8, 0.9_3_9_7, 0.9_5_9_9, 0.9_9_0_1, 1.0_0_0_0, 1.0_0_0_0, 0.9_8_8_2, 1.0_0_0_0, 1.0_0_0_0] )

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



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







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


														"""simple docstring"""


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







							def        __lowerCAmelCase      (  self	:  Any )      ->							Tuple:


														"""simple docstring"""


														_a     					=    load_image(
														    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
														    '''/img2img/sketch-mountains-input.jpg''' )
														_a     					=    init_image.resize((7_68, 5_12) )
														_a     					=    load_numpy(
														    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy''' )

														_a     					=    '''BAAI/AltDiffusion'''
														_a     					=    AltDiffusionImgaImgPipeline.from_pretrained(
														    lowerCAmelCase_							,      safety_checker=lowerCAmelCase_							,      )
														pipe.to(lowerCAmelCase_ )
														pipe.set_progress_bar_config(disable=lowerCAmelCase_ )
														pipe.enable_attention_slicing()

														_a     					=    '''A fantasy landscape, trending on artstation'''

														_a     					=    torch.manual_seed(0 )
														_a     					=    pipe(
														    prompt=lowerCAmelCase_							,      image=lowerCAmelCase_							,      strength=0.7_5							,      guidance_scale=7.5							,      generator=lowerCAmelCase_							,      output_type='''np'''							,      )
														_a     					=    output.images[0]

														assert image.shape == (5_12, 7_68, 3)
														# img2img is flaky across GPUs even in fp32, so using MAE here
														assert np.abs(expected_image - image ).max() < 1e-2







'''simple docstring'''


from typing import Callable, List, Optional, Union

import PIL
import torch
from transformers import (
    CLIPImageProcessor,
    CLIPSegForImageSegmentation,
    CLIPSegProcessor,
    CLIPTextModel,
    CLIPTokenizer,
)

from diffusers import DiffusionPipeline
from diffusers.configuration_utils import FrozenDict
from diffusers.models import AutoencoderKL, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
from diffusers.utils import deprecate, is_accelerate_available, logging


_snake_case				:				List[Any]       							=		logging.get_logger(__name__)  # pylint: disable=invalid-name

class       A   (		_a   ):







							def __init__(  self	:  Dict							,      lowerCAmelCase_	:  CLIPSegForImageSegmentation							,      lowerCAmelCase_	:  CLIPSegProcessor							,      lowerCAmelCase_	:  AutoencoderKL							,      lowerCAmelCase_	:  CLIPTextModel							,      lowerCAmelCase_	:  CLIPTokenizer							,      lowerCAmelCase_	:  UNetaDConditionModel							,      lowerCAmelCase_	:  Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]							,      lowerCAmelCase_	:  StableDiffusionSafetyChecker							,      lowerCAmelCase_	:  CLIPImageProcessor							,      )      ->							int:


														"""simple docstring"""


														super().__init__()

														if hasattr(scheduler.config							,      '''steps_offset''' ) and scheduler.config.steps_offset != 1:
																					_a     					=    (
																					    F'The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`'
																					    F' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure '
																					    '''to update the config accordingly as leaving `steps_offset` might led to incorrect results'''
																					    ''' in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,'''
																					    ''' it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`'''
																					    ''' file'''
																					)
																					deprecate('''steps_offset!=1'''							,      '''1.0.0'''							,      lowerCAmelCase_							,      standard_warn=lowerCAmelCase_ )
																					_a     					=    dict(scheduler.config )
																					_a     					=    1
																					_a     					=    FrozenDict(lowerCAmelCase_ )

														if hasattr(scheduler.config							,      '''skip_prk_steps''' ) and scheduler.config.skip_prk_steps is False:
																					_a     					=    (
																					    F'The configuration file of this scheduler: {scheduler} has not set the configuration'
																					    ''' `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make'''
																					    ''' sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to'''
																					    ''' incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face'''
																					    ''' Hub, it would be very nice if you could open a Pull request for the'''
																					    ''' `scheduler/scheduler_config.json` file'''
																					)
																					deprecate('''skip_prk_steps not set'''							,      '''1.0.0'''							,      lowerCAmelCase_							,      standard_warn=lowerCAmelCase_ )
																					_a     					=    dict(scheduler.config )
																					_a     					=    True
																					_a     					=    FrozenDict(lowerCAmelCase_ )

														if safety_checker is None:
																					logger.warning(
																					    F'You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure'
																					    ''' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered'''
																					    ''' results in services or applications open to the public. Both the diffusers team and Hugging Face'''
																					    ''' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling'''
																					    ''' it only for use-cases that involve analyzing network behavior or auditing its results. For more'''
																					    ''' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .''' )

														self.register_modules(
														    segmentation_model=lowerCAmelCase_							,      segmentation_processor=lowerCAmelCase_							,      vae=lowerCAmelCase_							,      text_encoder=lowerCAmelCase_							,      tokenizer=lowerCAmelCase_							,      unet=lowerCAmelCase_							,      scheduler=lowerCAmelCase_							,      safety_checker=lowerCAmelCase_							,      feature_extractor=lowerCAmelCase_							,      )







							def        __lowerCAmelCase      (  self	:  str							,      lowerCAmelCase_	:  Optional[Union[str, int]] = "auto" )      ->							Any:


														"""simple docstring"""


														if slice_size == "auto":
																					# half the attention head size is usually a good trade-off between
																					# speed and memory
																					_a     					=    self.unet.config.attention_head_dim // 2
														self.unet.set_attention_slice(lowerCAmelCase_ )







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


														"""simple docstring"""


														self.enable_attention_slicing(lowerCAmelCase_ )







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


														"""simple docstring"""


														if is_accelerate_available():
																					from accelerate import cpu_offload
														else:
																					raise ImportError('''Please install accelerate via `pip install accelerate`''' )

														_a     					=    torch.device('''cuda''' )

														for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]:
																					if cpu_offloaded_model is not None:
																												cpu_offload(lowerCAmelCase_							,      lowerCAmelCase_ )







							@property
							# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
							def        __lowerCAmelCase      (  self	:  Dict )      ->							List[str]:


														"""simple docstring"""


														if self.device != torch.device('''meta''' ) or not hasattr(self.unet							,      '''_hf_hook''' ):
																					return self.device
														for module in self.unet.modules():
																					if (
																					    hasattr(lowerCAmelCase_							,      '''_hf_hook''' )
																					    and hasattr(module._hf_hook							,      '''execution_device''' )
																					    and module._hf_hook.execution_device is not None
																					):
																												return torch.device(module._hf_hook.execution_device )
														return self.device







							@torch.no_grad()
							def __call__(  self	:  List[Any]							,      lowerCAmelCase_	:  Union[str, List[str]]							,      lowerCAmelCase_	:  Union[torch.FloatTensor, PIL.Image.Image]							,      lowerCAmelCase_	:  str							,      lowerCAmelCase_	:  int = 5_12							,      lowerCAmelCase_	:  int = 5_12							,      lowerCAmelCase_	:  int = 50							,      lowerCAmelCase_	:  float = 7.5							,      lowerCAmelCase_	:  Optional[Union[str, List[str]]] = None							,      lowerCAmelCase_	:  Optional[int] = 1							,      lowerCAmelCase_	:  float = 0.0							,      lowerCAmelCase_	:  Optional[torch.Generator] = None							,      lowerCAmelCase_	:  Optional[torch.FloatTensor] = None							,      lowerCAmelCase_	:  Optional[str] = "pil"							,      lowerCAmelCase_	:  bool = True							,      lowerCAmelCase_	:  Optional[Callable[[int, int, torch.FloatTensor], None]] = None							,      lowerCAmelCase_	:  int = 1							,      **lowerCAmelCase_	:  Any							,      )      ->							Tuple:


														"""simple docstring"""


														_a     					=    self.segmentation_processor(
														    text=[text]							,      images=[image]							,      padding='''max_length'''							,      return_tensors='''pt''' ).to(self.device )
														_a     					=    self.segmentation_model(**lowerCAmelCase_ )
														_a     					=    torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy()
														_a     					=    self.numpy_to_pil(lowerCAmelCase_ )[0].resize(image.size )

														# Run inpainting pipeline with the generated mask
														_a     					=    StableDiffusionInpaintPipeline(
														    vae=self.vae							,      text_encoder=self.text_encoder							,      tokenizer=self.tokenizer							,      unet=self.unet							,      scheduler=self.scheduler							,      safety_checker=self.safety_checker							,      feature_extractor=self.feature_extractor							,      )
														return inpainting_pipeline(
														    prompt=lowerCAmelCase_							,      image=lowerCAmelCase_							,      mask_image=lowerCAmelCase_							,      height=lowerCAmelCase_							,      width=lowerCAmelCase_							,      num_inference_steps=lowerCAmelCase_							,      guidance_scale=lowerCAmelCase_							,      negative_prompt=lowerCAmelCase_							,      num_images_per_prompt=lowerCAmelCase_							,      eta=lowerCAmelCase_							,      generator=lowerCAmelCase_							,      latents=lowerCAmelCase_							,      output_type=lowerCAmelCase_							,      return_dict=lowerCAmelCase_							,      callback=lowerCAmelCase_							,      callback_steps=lowerCAmelCase_							,      )

