code: 
  
  
  import math
  from dataclasses import dataclass
  from typing import List, Optional, Tuple, Union
  
  import numpy as np
  import torch
  
  from ..configuration_utils import ConfigMixin, register_to_config
  from ..utils import BaseOutput, logging, randn_tensor
  from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin
  
  
  SCREAMING_SNAKE_CASE__				:    Optional[Any]         =    logging.get_logger(__name__)  # pylint: disable=invalid-name
  
  
  @dataclass
  # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->EulerAncestralDiscrete
  class 		_SCREAMING_SNAKE_CASE    (	A    ):
       __SCREAMING_SNAKE_CASE    				=						42
       __SCREAMING_SNAKE_CASE    				=						None
  
  
  
  
  def       a__						(		snake_case__				:       Any	,      snake_case__				:       Tuple=0.999	,      snake_case__				:       Optional[Any]="cosine"	,      ):
    if alpha_transform_type == "cosine":
  
      def alpha_bar_fn(snake_case__				:       int    ):
        return math.cos((t + 0.008) / 1.008 * math.pi / 2    ) ** 2
  
    elif alpha_transform_type == "exp":
  
      def alpha_bar_fn(snake_case__				:       int    ):
        return math.exp(t * -12.0    )
  
    else:
      raise ValueError(f'''Unsupported alpha_tranform_type: {alpha_transform_type}'''    )
  
    _UpperCAmelCase		:       List[str]       =    []
    for i in range(snake_case__    ):
      _UpperCAmelCase		:       str       =    i / num_diffusion_timesteps
      _UpperCAmelCase		:       Tuple       =    (i + 1) / num_diffusion_timesteps
      betas.append(min(1 - alpha_bar_fn(snake_case__    ) / alpha_bar_fn(snake_case__    )	,      snake_case__    )    )
    return torch.tensor(snake_case__	,      dtype=torch.floataa    )
  
  
  
  
  
  class 		_SCREAMING_SNAKE_CASE    (	A       ,  A    ):
       __SCREAMING_SNAKE_CASE    				=						[e.name for e in KarrasDiffusionSchedulers]
       __SCREAMING_SNAKE_CASE    				=						1
  
  
       @register_to_config
       def __init__(     self       ,				A_ = 10_00       ,				A_ = 0.0_0_0_1       ,				A_ = 0.0_2       ,				A_ = "linear"       ,				A_ = None       ,				A_ = "epsilon"       ,				A_ = "linspace"       ,				A_ = 0       ,				):
         if trained_betas is not None:
           _UpperCAmelCase		:       Tuple       =    torch.tensor(A_       ,				dtype=torch.floataa						)
         elif beta_schedule == "linear":
           _UpperCAmelCase		:       List[Any]       =    torch.linspace(A_       ,				A_       ,				A_       ,				dtype=torch.floataa						)
         elif beta_schedule == "scaled_linear":
           # this schedule is very specific to the latent diffusion model.
           _UpperCAmelCase		:       int       =    (
               torch.linspace(beta_start**0.5       ,				beta_end**0.5       ,				A_       ,				dtype=torch.floataa						) ** 2
           )
         elif beta_schedule == "squaredcos_cap_v2":
           # Glide cosine schedule
           _UpperCAmelCase		:       int       =    betas_for_alpha_bar(A_						)
         else:
           raise NotImplementedError(F'''{beta_schedule} does is not implemented for {self.__class__}'''						)
  
         _UpperCAmelCase		:       Any       =    1.0 - self.betas
         _UpperCAmelCase		:       Optional[int]       =    torch.cumprod(self.alphas       ,				dim=0						)
  
         _UpperCAmelCase		:       int       =    np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5						)
         _UpperCAmelCase		:       Optional[Any]       =    np.concatenate([sigmas[::-1], [0.0]]						).astype(np.floataa						)
         _UpperCAmelCase		:       List[str]       =    torch.from_numpy(A_						)
  
         # setable values
         _UpperCAmelCase		:       Union[str, Any]       =    None
         _UpperCAmelCase		:       Union[str, Any]       =    np.linspace(0       ,				num_train_timesteps - 1       ,				A_       ,				dtype=A_						)[::-1].copy()
         _UpperCAmelCase		:       List[str]       =    torch.from_numpy(A_						)
         _UpperCAmelCase		:       Dict       =    False
  
  
       @property
       def 					__snake_case(     self						):
         # standard deviation of the initial noise distribution
         if self.config.timestep_spacing in ["linspace", "trailing"]:
           return self.sigmas.max()
  
         return (self.sigmas.max() ** 2 + 1) ** 0.5
  
  
       def 					__snake_case(     self       ,				A_       ,				A_						):
         if isinstance(A_       ,				torch.Tensor						):
           _UpperCAmelCase		:       str       =    timestep.to(self.timesteps.device						)
         _UpperCAmelCase		:       int       =    (self.timesteps == timestep).nonzero().item()
         _UpperCAmelCase		:       Optional[Any]       =    self.sigmas[step_index]
         _UpperCAmelCase		:       Union[str, Any]       =    sample / ((sigma**2 + 1) ** 0.5)
         _UpperCAmelCase		:       str       =    True
         return sample
  
  
       def 					__snake_case(     self       ,				A_       ,				A_ = None						):
         _UpperCAmelCase		:       Optional[int]       =    num_inference_steps
  
         # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
         if self.config.timestep_spacing == "linspace":
           _UpperCAmelCase		:       Any       =    np.linspace(0       ,				self.config.num_train_timesteps - 1       ,				A_       ,				dtype=A_						)[
               ::-1
           ].copy()
         elif self.config.timestep_spacing == "leading":
           _UpperCAmelCase		:       Dict       =    self.config.num_train_timesteps // self.num_inference_steps
           # creates integer timesteps by multiplying by ratio
           # casting to int to avoid issues when num_inference_step is power of 3
           _UpperCAmelCase		:       List[Any]       =    (np.arange(0       ,				A_						) * step_ratio).round()[::-1].copy().astype(A_						)
           timesteps += self.config.steps_offset
         elif self.config.timestep_spacing == "trailing":
           _UpperCAmelCase		:       Any       =    self.config.num_train_timesteps / self.num_inference_steps
           # creates integer timesteps by multiplying by ratio
           # casting to int to avoid issues when num_inference_step is power of 3
           _UpperCAmelCase		:       Tuple       =    (np.arange(self.config.num_train_timesteps       ,				0       ,				-step_ratio						)).round().copy().astype(A_						)
           timesteps -= 1
         else:
           raise ValueError(
               F'''{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.'''						)
  
         _UpperCAmelCase		:       Dict       =    np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5						)
         _UpperCAmelCase		:       str       =    np.interp(A_       ,				np.arange(0       ,				len(A_						)						)       ,				A_						)
         _UpperCAmelCase		:       int       =    np.concatenate([sigmas, [0.0]]						).astype(np.floataa						)
         _UpperCAmelCase		:       Optional[Any]       =    torch.from_numpy(A_						).to(device=A_						)
         if str(A_						).startswith("""mps"""						):
           # mps does not support float64
           _UpperCAmelCase		:       int       =    torch.from_numpy(A_						).to(A_       ,				dtype=torch.floataa						)
         else:
           _UpperCAmelCase		:       Union[str, Any]       =    torch.from_numpy(A_						).to(device=A_						)
  
  
       def 					__snake_case(     self       ,				A_       ,				A_       ,				A_       ,				A_ = None       ,				A_ = True       ,				):
  
         if (
             isinstance(A_       ,				A_						)
             or isinstance(A_       ,				torch.IntTensor						)
             or isinstance(A_       ,				torch.LongTensor						)
         ):
           raise ValueError(
               (
                   """Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"""
                   """ `EulerDiscreteScheduler.step()` is not supported. Make sure to pass"""
                   """ one of the `scheduler.timesteps` as a timestep."""
               )       ,				)
  
         if not self.is_scale_input_called:
           logger.warning(
               """The `scale_model_input` function should be called before `step` to ensure correct denoising. """
               """See `StableDiffusionPipeline` for a usage example."""						)
  
         if isinstance(A_       ,				torch.Tensor						):
           _UpperCAmelCase		:       int       =    timestep.to(self.timesteps.device						)
  
         _UpperCAmelCase		:       Dict       =    (self.timesteps == timestep).nonzero().item()
         _UpperCAmelCase		:       Tuple       =    self.sigmas[step_index]
  
         # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
         if self.config.prediction_type == "epsilon":
           _UpperCAmelCase		:       int       =    sample - sigma * model_output
         elif self.config.prediction_type == "v_prediction":
           # * c_out + input * c_skip
           _UpperCAmelCase		:       int       =    model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
         elif self.config.prediction_type == "sample":
           raise NotImplementedError("""prediction_type not implemented yet: sample"""						)
         else:
           raise ValueError(
               F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`'''						)
  
         _UpperCAmelCase		:       int       =    self.sigmas[step_index]
         _UpperCAmelCase		:       Union[str, Any]       =    self.sigmas[step_index + 1]
         _UpperCAmelCase		:       List[str]       =    (sigma_to**2 * (sigma_from**2 - sigma_to**2) / sigma_from**2) ** 0.5
         _UpperCAmelCase		:       Optional[Any]       =    (sigma_to**2 - sigma_up**2) ** 0.5
  
         # 2. Convert to an ODE derivative
         _UpperCAmelCase		:       Union[str, Any]       =    (sample - pred_original_sample) / sigma
  
         _UpperCAmelCase		:       Optional[Any]       =    sigma_down - sigma
  
         _UpperCAmelCase		:       str       =    sample + derivative * dt
  
         _UpperCAmelCase		:       Optional[int]       =    model_output.device
         _UpperCAmelCase		:       Optional[Any]       =    randn_tensor(model_output.shape       ,				dtype=model_output.dtype       ,				device=A_       ,				generator=A_						)
  
         _UpperCAmelCase		:       Tuple       =    prev_sample + noise * sigma_up
  
         if not return_dict:
           return (prev_sample,)
  
         return EulerAncestralDiscreteSchedulerOutput(
             prev_sample=A_       ,				pred_original_sample=A_						)
  
  
       def 					__snake_case(     self       ,				A_       ,				A_       ,				A_       ,				):
         # Make sure sigmas and timesteps have the same device and dtype as original_samples
         _UpperCAmelCase		:       int       =    self.sigmas.to(device=original_samples.device       ,				dtype=original_samples.dtype						)
         if original_samples.device.type == "mps" and torch.is_floating_point(A_						):
           # mps does not support float64
           _UpperCAmelCase		:       Optional[Any]       =    self.timesteps.to(original_samples.device       ,				dtype=torch.floataa						)
           _UpperCAmelCase		:       Optional[int]       =    timesteps.to(original_samples.device       ,				dtype=torch.floataa						)
         else:
           _UpperCAmelCase		:       Tuple       =    self.timesteps.to(original_samples.device						)
           _UpperCAmelCase		:       Any       =    timesteps.to(original_samples.device						)
  
         _UpperCAmelCase		:       Tuple       =    [(schedule_timesteps == t).nonzero().item() for t in timesteps]
  
         _UpperCAmelCase		:       List[Any]       =    sigmas[step_indices].flatten()
         while len(sigma.shape						) < len(original_samples.shape						):
           _UpperCAmelCase		:       List[str]       =    sigma.unsqueeze(-1						)
  
         _UpperCAmelCase		:       Union[str, Any]       =    original_samples + noise * sigma
         return noisy_samples
  
  
  
  
       def __len__(     self						):
         return self.config.num_train_timesteps
  
  
  
  
  
  
style_context: 
  
  
  from dataclasses import dataclass
  from enum import Enum
  from typing import List, Optional, Union
  
  import numpy as np
  import PIL
  from PIL import Image
  
  from ...utils import BaseOutput, is_torch_available, is_transformers_available
  
  
  @dataclass
  class 		_SCREAMING_SNAKE_CASE    (	A    ):
       __SCREAMING_SNAKE_CASE    				=						{
           '''sld_warmup_steps''': 1_5,
           '''sld_guidance_scale''': 2_0,
           '''sld_threshold''': 0.0,
           '''sld_momentum_scale''': 0.0,
           '''sld_mom_beta''': 0.0,
       }
       __SCREAMING_SNAKE_CASE    				=						{
           '''sld_warmup_steps''': 1_0,
           '''sld_guidance_scale''': 1_0_0_0,
           '''sld_threshold''': 0.01,
           '''sld_momentum_scale''': 0.3,
           '''sld_mom_beta''': 0.4,
       }
       __SCREAMING_SNAKE_CASE    				=						{
           '''sld_warmup_steps''': 7,
           '''sld_guidance_scale''': 2_0_0_0,
           '''sld_threshold''': 0.025,
           '''sld_momentum_scale''': 0.5,
           '''sld_mom_beta''': 0.7,
       }
       __SCREAMING_SNAKE_CASE    				=						{
           '''sld_warmup_steps''': 0,
           '''sld_guidance_scale''': 5_0_0_0,
           '''sld_threshold''': 1.0,
           '''sld_momentum_scale''': 0.5,
           '''sld_mom_beta''': 0.7,
       }
  
  
  @dataclass
  class 		_SCREAMING_SNAKE_CASE    (	A    ):
       __SCREAMING_SNAKE_CASE    				=						42
       __SCREAMING_SNAKE_CASE    				=						42
       __SCREAMING_SNAKE_CASE    				=						42
       __SCREAMING_SNAKE_CASE    				=						42
  
  
  if is_transformers_available() and is_torch_available():
   from .pipeline_stable_diffusion_safe import StableDiffusionPipelineSafe
   from .safety_checker import SafeStableDiffusionSafetyChecker
  
  
  
  
  
  