



'''simple docstring'''






import random
import unittest

import torch

from diffusers import IFImgaImgPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin



@skip_mps
class 							lowercase (						_lowerCamelCase      ,      _lowerCamelCase      ,      unittest.TestCase       ):


 """simple docstring"""


 UpperCAmelCase					=						IFImgaImgPipeline
 UpperCAmelCase					=						TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""width""", """height"""}
 UpperCAmelCase					=						TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
 UpperCAmelCase					=						PipelineTesterMixin.required_optional_params - {"""latents"""}







 def _snake_case				(							self							)	->     Tuple:
        return self._get_dummy_components()







 def _snake_case				(							self						,a_						,a_=0							)	->     List[Any]:
        if str(a_							).startswith("""mps"""							):
               _UpperCAmelCase						:		List[str]      =				torch.manual_seed(a_							)
        else:
               _UpperCAmelCase						:		Optional[Any]      =				torch.Generator(device=a_							).manual_seed(a_							)

        _UpperCAmelCase						:		int      =				floats_tensor((1, 3, 32, 32)						,rng=random.Random(a_							)							).to(a_							)

        _UpperCAmelCase						:		Dict      =				{
            """prompt""": """A painting of a squirrel eating a burger""",
            """image""": image,
            """generator""": generator,
            """num_inference_steps""": 2,
            """output_type""": """numpy""",
        }

        return inputs







 def _snake_case				(							self							)	->     Optional[Any]:
        self._test_save_load_optional_components()







 @unittest.skipIf(
     torch_device != """cuda""" or not is_xformers_available()						,reason="""XFormers attention is only available with CUDA and `xformers` installed"""						,)
 def _snake_case				(							self							)	->     Dict:
        self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3							)







 @unittest.skipIf(torch_device != """cuda"""						,reason="""float16 requires CUDA"""							)
 def _snake_case				(							self							)	->     str:
        # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
        super().test_save_load_floataa(expected_max_diff=1E-1							)







 @unittest.skipIf(torch_device != """cuda"""						,reason="""float16 requires CUDA"""							)
 def _snake_case				(							self							)	->     List[Any]:
        super().test_floataa_inference(expected_max_diff=1E-1							)







 def _snake_case				(							self							)	->     Union[str, Any]:
        self._test_attention_slicing_forward_pass(expected_max_diff=1E-2							)







 def _snake_case				(							self							)	->     Tuple:
        self._test_save_load_local()







 def _snake_case				(							self							)	->     Any:
        self._test_inference_batch_single_identical(
            expected_max_diff=1E-2						,)








'''simple docstring'''






from typing import Any, Callable, Dict, List, Optional, Union

import PIL.Image
import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionImgaImgPipeline,
    StableDiffusionInpaintPipelineLegacy,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.configuration_utils import FrozenDict
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.utils import deprecate, logging


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



class 							lowercase (						_lowerCamelCase       ):


 """simple docstring"""


 UpperCAmelCase					=						["""safety_checker""", """feature_extractor"""]







 def __init__(							self						,a_						,a_						,a_						,a_						,a_						,a_						,a_						,a_ = True						,)	->     int:
        super().__init__()
        if hasattr(scheduler.config						,"""steps_offset"""							) and scheduler.config.steps_offset != 1:
               _UpperCAmelCase						:		Tuple      =				(
                   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"""						,a_						,standard_warn=a_							)
               _UpperCAmelCase						:		Any      =				dict(scheduler.config							)
               _UpperCAmelCase						:		str      =				1
               _UpperCAmelCase						:		Any      =				FrozenDict(a_							)

        self.register_modules(
            vae=a_						,text_encoder=a_						,tokenizer=a_						,unet=a_						,scheduler=a_						,safety_checker=a_						,feature_extractor=a_						,)
        self.register_to_config(requires_safety_checker=a_							)







 @property
 def _snake_case				(							self							)	->     Dict[str, Any]:
        return {k: getattr(self						,a_							) for k in self.config.keys() if not k.startswith("""_"""							)}







 def _snake_case				(							self						,a_ = "auto"							)	->     Union[str, Any]:
        if slice_size == "auto":
               # half the attention head size is usually a good trade-off between
               # speed and memory
               _UpperCAmelCase						:		Optional[int]      =				self.unet.config.attention_head_dim // 2
        self.unet.set_attention_slice(a_							)







 def _snake_case				(							self							)	->     Tuple:
        self.enable_attention_slicing(a_							)







 @torch.no_grad()
 def _snake_case				(							self						,a_						,a_						,a_						,a_ = 0.8						,a_ = 50						,a_ = 7.5						,a_ = None						,a_ = 1						,a_ = 0.0						,a_ = None						,a_ = "pil"						,a_ = True						,a_ = None						,a_ = 1						,)	->     List[Any]:
        # For more information on how this function works, please see: https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionImg2ImgPipeline
        return StableDiffusionInpaintPipelineLegacy(**self.components							)(
            prompt=a_						,image=a_						,mask_image=a_						,strength=a_						,num_inference_steps=a_						,guidance_scale=a_						,negative_prompt=a_						,num_images_per_prompt=a_						,eta=a_						,generator=a_						,output_type=a_						,return_dict=a_						,callback=a_						,)







 @torch.no_grad()
 def _snake_case				(							self						,a_						,a_						,a_ = 0.8						,a_ = 50						,a_ = 7.5						,a_ = None						,a_ = 1						,a_ = 0.0						,a_ = None						,a_ = "pil"						,a_ = True						,a_ = None						,a_ = 1						,**a_						,)	->     Tuple:
        # For more information on how this function works, please see: https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionImg2ImgPipeline
        return StableDiffusionImgaImgPipeline(**self.components							)(
            prompt=a_						,image=a_						,strength=a_						,num_inference_steps=a_						,guidance_scale=a_						,negative_prompt=a_						,num_images_per_prompt=a_						,eta=a_						,generator=a_						,output_type=a_						,return_dict=a_						,callback=a_						,callback_steps=a_						,)







 @torch.no_grad()
 def _snake_case				(							self						,a_						,a_ = 512						,a_ = 512						,a_ = 50						,a_ = 7.5						,a_ = None						,a_ = 1						,a_ = 0.0						,a_ = None						,a_ = None						,a_ = "pil"						,a_ = True						,a_ = None						,a_ = 1						,)	->     List[str]:
        # For more information on how this function https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionPipeline
        return StableDiffusionPipeline(**self.components							)(
            prompt=a_						,height=a_						,width=a_						,num_inference_steps=a_						,guidance_scale=a_						,negative_prompt=a_						,num_images_per_prompt=a_						,eta=a_						,generator=a_						,latents=a_						,output_type=a_						,return_dict=a_						,callback=a_						,callback_steps=a_						,)



