






"""simple docstring"""





from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block







@dataclass
class 						_a  (		lowercase_       ):





   '''simple docstring'''






   UpperCamelCase__     	=							42







class 						_a  (		lowercase_							,	lowercase_       ):





   '''simple docstring'''






   @register_to_config
   def __init__(       self					, UpperCAmelCase_ = None					, UpperCAmelCase_ = 3					, UpperCAmelCase_ = 3					, UpperCAmelCase_ = False					, UpperCAmelCase_ = "positional"					, UpperCAmelCase_ = 0					, UpperCAmelCase_ = True					, UpperCAmelCase_ = ("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D")					, UpperCAmelCase_ = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D")					, UpperCAmelCase_ = (224, 448, 672, 896)					, UpperCAmelCase_ = 2					, UpperCAmelCase_ = 1					, UpperCAmelCase_ = 1					, UpperCAmelCase_ = "conv"					, UpperCAmelCase_ = "conv"					, UpperCAmelCase_ = "silu"					, UpperCAmelCase_ = 8					, UpperCAmelCase_ = 32					, UpperCAmelCase_ = 1E-5					, UpperCAmelCase_ = "default"					, UpperCAmelCase_ = True					, UpperCAmelCase_ = None					, UpperCAmelCase_ = None					, )			->   int:




          '''simple docstring'''




          super().__init__()

          lowercase__:							Dict         =     sample_size
          lowercase__:							Optional[int]         =     block_out_channels[0] * 4

          # Check inputs
          if len(UpperCAmelCase_) != len(UpperCAmelCase_):
                 raise ValueError(
                     F"""Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}.""")

          if len(UpperCAmelCase_) != len(UpperCAmelCase_):
                 raise ValueError(
                     F"""Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}.""")

          # input
          lowercase__:							Union[str, Any]         =     nn.Convad(UpperCAmelCase_					, block_out_channels[0]					, kernel_size=3					, padding=(1, 1))

          # time
          if time_embedding_type == "fourier":
                 lowercase__:							str         =     GaussianFourierProjection(embedding_size=block_out_channels[0]					, scale=16)
                 lowercase__:							Tuple         =     2 * block_out_channels[0]
          elif time_embedding_type == "positional":
                 lowercase__:							Any         =     Timesteps(block_out_channels[0]					, UpperCAmelCase_					, UpperCAmelCase_)
                 lowercase__:							str         =     block_out_channels[0]

          lowercase__:							List[str]         =     TimestepEmbedding(UpperCAmelCase_					, UpperCAmelCase_)

          # class embedding
          if class_embed_type is None and num_class_embeds is not None:
                 lowercase__:							Tuple         =     nn.Embedding(UpperCAmelCase_					, UpperCAmelCase_)
          elif class_embed_type == "timestep":
                 lowercase__:							Optional[Any]         =     TimestepEmbedding(UpperCAmelCase_					, UpperCAmelCase_)
          elif class_embed_type == "identity":
                 lowercase__:							List[str]         =     nn.Identity(UpperCAmelCase_					, UpperCAmelCase_)
          else:
                 lowercase__:							Tuple         =     None

          lowercase__:							str         =     nn.ModuleList([])
          lowercase__:							Optional[Any]         =     None
          lowercase__:							List[str]         =     nn.ModuleList([])

          # down
          lowercase__:							Optional[int]         =     block_out_channels[0]
          for i, down_block_type in enumerate(UpperCAmelCase_):
                 lowercase__:							List[Any]         =     output_channel
                 lowercase__:							Any         =     block_out_channels[i]
                 lowercase__:							List[str]         =     i == len(UpperCAmelCase_) - 1

                 lowercase__:							Any         =     get_down_block(
                     UpperCAmelCase_					, num_layers=UpperCAmelCase_					, in_channels=UpperCAmelCase_					, out_channels=UpperCAmelCase_					, temb_channels=UpperCAmelCase_					, add_downsample=not is_final_block					, resnet_eps=UpperCAmelCase_					, resnet_act_fn=UpperCAmelCase_					, resnet_groups=UpperCAmelCase_					, attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel					, downsample_padding=UpperCAmelCase_					, resnet_time_scale_shift=UpperCAmelCase_					, downsample_type=UpperCAmelCase_					, )
                 self.down_blocks.append(UpperCAmelCase_)

          # mid
          lowercase__:							Optional[Any]         =     UNetMidBlockaD(
              in_channels=block_out_channels[-1]					, temb_channels=UpperCAmelCase_					, resnet_eps=UpperCAmelCase_					, resnet_act_fn=UpperCAmelCase_					, output_scale_factor=UpperCAmelCase_					, resnet_time_scale_shift=UpperCAmelCase_					, attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1]					, resnet_groups=UpperCAmelCase_					, add_attention=UpperCAmelCase_					, )

          # up
          lowercase__:							str         =     list(reversed(UpperCAmelCase_))
          lowercase__:							List[str]         =     reversed_block_out_channels[0]
          for i, up_block_type in enumerate(UpperCAmelCase_):
                 lowercase__:							str         =     output_channel
                 lowercase__:							str         =     reversed_block_out_channels[i]
                 lowercase__:							List[Any]         =     reversed_block_out_channels[min(i + 1					, len(UpperCAmelCase_) - 1)]

                 lowercase__:							str         =     i == len(UpperCAmelCase_) - 1

                 lowercase__:							Optional[int]         =     get_up_block(
                     UpperCAmelCase_					, num_layers=layers_per_block + 1					, in_channels=UpperCAmelCase_					, out_channels=UpperCAmelCase_					, prev_output_channel=UpperCAmelCase_					, temb_channels=UpperCAmelCase_					, add_upsample=not is_final_block					, resnet_eps=UpperCAmelCase_					, resnet_act_fn=UpperCAmelCase_					, resnet_groups=UpperCAmelCase_					, attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel					, resnet_time_scale_shift=UpperCAmelCase_					, upsample_type=UpperCAmelCase_					, )
                 self.up_blocks.append(UpperCAmelCase_)
                 lowercase__:							Dict         =     output_channel

          # out
          lowercase__:							Dict         =     norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4					, 32)
          lowercase__:							Optional[Any]         =     nn.GroupNorm(num_channels=block_out_channels[0]					, num_groups=UpperCAmelCase_					, eps=UpperCAmelCase_)
          lowercase__:							List[str]         =     nn.SiLU()
          lowercase__:							Tuple         =     nn.Convad(block_out_channels[0]					, UpperCAmelCase_					, kernel_size=3					, padding=1)





   def __lowercase							(       self					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_ = None					, UpperCAmelCase_ = True					, )			->   Union[UNetaDOutput, Tuple]:




          '''simple docstring'''




          if self.config.center_input_sample:
                 lowercase__:							Tuple         =     2 * sample - 1.0

          # 1. time
          lowercase__:							Dict         =     timestep
          if not torch.is_tensor(UpperCAmelCase_):
                 lowercase__:							str         =     torch.tensor([timesteps]					, dtype=torch.long					, device=sample.device)
          elif torch.is_tensor(UpperCAmelCase_) and len(timesteps.shape) == 0:
                 lowercase__:							int         =     timesteps[None].to(sample.device)

          # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
          lowercase__:							List[Any]         =     timesteps * torch.ones(sample.shape[0]					, dtype=timesteps.dtype					, device=timesteps.device)

          lowercase__:							Union[str, Any]         =     self.time_proj(UpperCAmelCase_)

          # timesteps does not contain any weights and will always return f32 tensors
          # but time_embedding might actually be running in fp16. so we need to cast here.
          # there might be better ways to encapsulate this.
          lowercase__:							Any         =     t_emb.to(dtype=self.dtype)
          lowercase__:							Tuple         =     self.time_embedding(UpperCAmelCase_)

          if self.class_embedding is not None:
                 if class_labels is None:
                        raise ValueError("class_labels should be provided when doing class conditioning")

                 if self.config.class_embed_type == "timestep":
                        lowercase__:							Dict         =     self.time_proj(UpperCAmelCase_)

                 lowercase__:							Any         =     self.class_embedding(UpperCAmelCase_).to(dtype=self.dtype)
                 lowercase__:							str         =     emb + class_emb

          # 2. pre-process
          lowercase__:							List[Any]         =     sample
          lowercase__:							Dict         =     self.conv_in(UpperCAmelCase_)

          # 3. down
          lowercase__:							Optional[Any]         =     (sample,)
          for downsample_block in self.down_blocks:
                 if hasattr(UpperCAmelCase_					, "skip_conv"):
                        lowercase__    ,      lowercase__    ,      lowercase__:							str         =     downsample_block(
                            hidden_states=UpperCAmelCase_					, temb=UpperCAmelCase_					, skip_sample=UpperCAmelCase_)
                 else:
                        lowercase__    ,      lowercase__:							Dict         =     downsample_block(hidden_states=UpperCAmelCase_					, temb=UpperCAmelCase_)

                 down_block_res_samples += res_samples

          # 4. mid
          lowercase__:							Union[str, Any]         =     self.mid_block(UpperCAmelCase_					, UpperCAmelCase_)

          # 5. up
          lowercase__:							List[Any]         =     None
          for upsample_block in self.up_blocks:
                 lowercase__:							Any         =     down_block_res_samples[-len(upsample_block.resnets) :]
                 lowercase__:							Optional[int]         =     down_block_res_samples[: -len(upsample_block.resnets)]

                 if hasattr(UpperCAmelCase_					, "skip_conv"):
                        lowercase__    ,      lowercase__:							int         =     upsample_block(UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_)
                 else:
                        lowercase__:							int         =     upsample_block(UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_)

        # 6. post-process
          lowercase__:							Union[str, Any]         =     self.conv_norm_out(UpperCAmelCase_)
          lowercase__:							Tuple         =     self.conv_act(UpperCAmelCase_)
          lowercase__:							Tuple         =     self.conv_out(UpperCAmelCase_)

          if skip_sample is not None:
                 sample += skip_sample

          if self.config.time_embedding_type == "fourier":
                 lowercase__:							Tuple         =     timesteps.reshape((sample.shape[0], *([1] * len(sample.shape[1:]))))
                 lowercase__:							str         =     sample / timesteps

          if not return_dict:
                 return (sample,)

          return UNetaDOutput(sample=UpperCAmelCase_)












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


UpperCamelCase__            =     logging.get_logger(__name__)  # pylint: disable=invalid-name
class      a__       (   snake_case__ ):
						_a				:       Tuple   =       ["""safety_checker""", """feature_extractor"""]






						def __init__(  self						,     _A						,     _A						,     _A						,     _A						,     _A						,     _A						,     _A						,     _A = True						,     ):




											"""simple docstring"""



											super().__init__()
											if hasattr(scheduler.config						,     "steps_offset"     ) and scheduler.config.steps_offset != 1:
																__lowerCAmelCase							  =			(
																    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     )
																__lowerCAmelCase							  =			dict(scheduler.config     )
																__lowerCAmelCase							  =			1
																__lowerCAmelCase							  =			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 							__SCREAMING_SNAKE_CASE(  self     ):




											"""simple docstring"""



											return {k: getattr(self						,     _A     ) for k in self.config.keys() if not k.startswith("_"     )}






						def 							__SCREAMING_SNAKE_CASE(  self						,     _A = "auto"     ):




											"""simple docstring"""



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






						def 							__SCREAMING_SNAKE_CASE(  self     ):




											"""simple docstring"""



											self.enable_attention_slicing(_A     )






						@torch.no_grad()
						def 							__SCREAMING_SNAKE_CASE(  self						,     _A						,     _A						,     _A						,     _A = 0.8						,     _A = 5_0						,     _A = 7.5						,     _A = None						,     _A = 1						,     _A = 0.0						,     _A = None						,     _A = "pil"						,     _A = True						,     _A = None						,     _A = 1						,     ):




											"""simple docstring"""



											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 							__SCREAMING_SNAKE_CASE(  self						,     _A						,     _A						,     _A = 0.8						,     _A = 5_0						,     _A = 7.5						,     _A = None						,     _A = 1						,     _A = 0.0						,     _A = None						,     _A = "pil"						,     _A = True						,     _A = None						,     _A = 1						,     **_A						,     ):




											"""simple docstring"""



											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 							__SCREAMING_SNAKE_CASE(  self						,     _A						,     _A = 5_1_2						,     _A = 5_1_2						,     _A = 5_0						,     _A = 7.5						,     _A = None						,     _A = 1						,     _A = 0.0						,     _A = None						,     _A = None						,     _A = "pil"						,     _A = True						,     _A = None						,     _A = 1						,     ):




											"""simple docstring"""



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




