

'''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


UpperCAmelCase				   =  logging.get_logger(__name__)  # pylint: disable=invalid-name


class   lowerCAmelCase     (      _UpperCAmelCase   ):
       lowerCAmelCase_		= ["safety_checker", "feature_extractor"]







       def __init__(							self			: str						,      __lowercase			: str						,      __lowercase			: Tuple						,      __lowercase			: str						,      __lowercase			: str						,      __lowercase			: Optional[int]						,      __lowercase			: List[Any]						,      __lowercase			: Tuple						,      __lowercase			: Dict = True						,      ):







            """simple docstring"""







            super().__init__()
            if hasattr(scheduler.config						,      'steps_offset'      ) and scheduler.config.steps_offset != 1:
                 __lowercase					=(
                     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'						,      __lowercase						,      standard_warn=__lowercase      )
                 __lowercase					=dict(scheduler.config      )
                 __lowercase					=1
                 __lowercase					=FrozenDict(__lowercase      )

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







       @property
       def 			snake_case   (							self			: List[str]      ):







            """simple docstring"""







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







       def 			snake_case   (							self			: str						,      __lowercase			: Optional[int] = "auto"      ):







            """simple docstring"""







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







       def 			snake_case   (							self			: List[Any]      ):







            """simple docstring"""







            self.enable_attention_slicing(__lowercase      )







       @torch.no_grad()
       def 			snake_case   (							self			: List[str]						,      __lowercase			: Union[str, Any]						,      __lowercase			: Dict						,      __lowercase			: Optional[Any]						,      __lowercase			: List[Any] = 0.8						,      __lowercase			: Optional[int] = 50						,      __lowercase			: Optional[int] = 7.5						,      __lowercase			: Union[str, Any] = None						,      __lowercase			: int = 1						,      __lowercase			: Union[str, Any] = 0.0						,      __lowercase			: Optional[Any] = None						,      __lowercase			: Tuple = "pil"						,      __lowercase			: int = True						,      __lowercase			: List[Any] = None						,      __lowercase			: Dict = 1						,      ):







            """simple docstring"""







            return StableDiffusionInpaintPipelineLegacy(**self.components      )(
                prompt=__lowercase						,      image=__lowercase						,      mask_image=__lowercase						,      strength=__lowercase						,      num_inference_steps=__lowercase						,      guidance_scale=__lowercase						,      negative_prompt=__lowercase						,      num_images_per_prompt=__lowercase						,      eta=__lowercase						,      generator=__lowercase						,      output_type=__lowercase						,      return_dict=__lowercase						,      callback=__lowercase						,      )







       @torch.no_grad()
       def 			snake_case   (							self			: List[Any]						,      __lowercase			: List[str]						,      __lowercase			: Optional[int]						,      __lowercase			: Optional[int] = 0.8						,      __lowercase			: str = 50						,      __lowercase			: Dict = 7.5						,      __lowercase			: Tuple = None						,      __lowercase			: Optional[Any] = 1						,      __lowercase			: Tuple = 0.0						,      __lowercase			: Dict = None						,      __lowercase			: Any = "pil"						,      __lowercase			: List[str] = True						,      __lowercase			: Dict = None						,      __lowercase			: Dict = 1						,      **__lowercase			: Dict						,      ):







            """simple docstring"""







            return StableDiffusionImgaImgPipeline(**self.components      )(
                prompt=__lowercase						,      image=__lowercase						,      strength=__lowercase						,      num_inference_steps=__lowercase						,      guidance_scale=__lowercase						,      negative_prompt=__lowercase						,      num_images_per_prompt=__lowercase						,      eta=__lowercase						,      generator=__lowercase						,      output_type=__lowercase						,      return_dict=__lowercase						,      callback=__lowercase						,      callback_steps=__lowercase						,      )







       @torch.no_grad()
       def 			snake_case   (							self			: Dict						,      __lowercase			: Dict						,      __lowercase			: Any = 512						,      __lowercase			: Tuple = 512						,      __lowercase			: Optional[Any] = 50						,      __lowercase			: Dict = 7.5						,      __lowercase			: int = None						,      __lowercase			: Union[str, Any] = 1						,      __lowercase			: Tuple = 0.0						,      __lowercase			: str = None						,      __lowercase			: List[str] = None						,      __lowercase			: str = "pil"						,      __lowercase			: Union[str, Any] = True						,      __lowercase			: Dict = None						,      __lowercase			: List[str] = 1						,      ):







            """simple docstring"""







            return StableDiffusionPipeline(**self.components      )(
                prompt=__lowercase						,      height=__lowercase						,      width=__lowercase						,      num_inference_steps=__lowercase						,      guidance_scale=__lowercase						,      negative_prompt=__lowercase						,      num_images_per_prompt=__lowercase						,      eta=__lowercase						,      generator=__lowercase						,      latents=__lowercase						,      output_type=__lowercase						,      return_dict=__lowercase						,      callback=__lowercase						,      callback_steps=__lowercase						,      )





'''simple docstring'''

from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
       import PIL


UpperCAmelCase				   =  logging.get_logger(__name__)


class   lowerCAmelCase     (      A   ):
       lowerCAmelCase_		= ["pixel_values"]







       def __init__(							self			: Dict						,      __lowercase			: bool = True						,      __lowercase			: Dict[str, int] = None						,      __lowercase			: bool = True						,      __lowercase			: Dict[str, int] = None						,      __lowercase			: PILImageResampling = PILImageResampling.BICUBIC						,      __lowercase			: bool = True						,      __lowercase			: Union[int, float] = 1 / 255						,      __lowercase			: bool = True						,      __lowercase			: Optional[Union[float, List[float]]] = None						,      __lowercase			: Optional[Union[float, List[float]]] = None						,      **__lowercase			: Any						,      ):







            """simple docstring"""







            super().__init__(**__lowercase      )
            __lowercase					=crop_size if crop_size is not None else {'height': 256, 'width': 256}
            __lowercase					=get_size_dict(__lowercase						,      param_name='crop_size'      )
            __lowercase					=size if size is not None else {'height': 224, 'width': 224}
            __lowercase					=get_size_dict(__lowercase      )

            __lowercase					=do_center_crop
            __lowercase					=crop_size
            __lowercase					=do_resize
            __lowercase					=size
            __lowercase					=resample
            __lowercase					=do_rescale
            __lowercase					=rescale_factor
            __lowercase					=do_normalize
            __lowercase					=image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
            __lowercase					=image_std if image_std is not None else IMAGENET_DEFAULT_STD







       def 			snake_case   (							self			: int						,      __lowercase			: np.ndarray						,      __lowercase			: Dict[str, int]						,      __lowercase			: Optional[int] = None						,      __lowercase			: Optional[Union[str, ChannelDimension]] = None						,      **__lowercase			: Optional[Any]						,      ):







            """simple docstring"""







            __lowercase					=self.size if size is None else size
            __lowercase					=get_size_dict(__lowercase      )
            __lowercase					=get_size_dict(__lowercase						,      param_name='crop_size'      )

            __lowercase		,     __lowercase					=get_image_size(__lowercase      )
            __lowercase					=min(__lowercase						,      __lowercase      )
            __lowercase					=(size['height'] / crop_size['height']) * min_dim
            __lowercase					=(size['width'] / crop_size['width']) * min_dim
            return center_crop(__lowercase						,      size=(cropped_height, cropped_width)						,      data_format=__lowercase						,      **__lowercase      )







       def 			snake_case   (							self			: str						,      __lowercase			: np.ndarray						,      __lowercase			: Dict[str, int]						,      __lowercase			: PILImageResampling = PIL.Image.BICUBIC						,      __lowercase			: Optional[Union[str, ChannelDimension]] = None						,      **__lowercase			: Optional[int]						,      ):







            """simple docstring"""







            __lowercase					=get_size_dict(__lowercase      )
            if "height" not in size or "width" not in size:
                 raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}'''      )
            return resize(
                __lowercase						,      size=(size['height'], size['width'])						,      resample=__lowercase						,      data_format=__lowercase						,      **__lowercase      )







       def 			snake_case   (							self			: Dict						,      __lowercase			: np.ndarray						,      __lowercase			: Union[int, float]						,      __lowercase			: Optional[Union[str, ChannelDimension]] = None						,      **__lowercase			: Dict						,      ):







            """simple docstring"""







            return rescale(__lowercase						,      scale=__lowercase						,      data_format=__lowercase						,      **__lowercase      )







       def 			snake_case   (							self			: Union[str, Any]						,      __lowercase			: np.ndarray						,      __lowercase			: Union[float, List[float]]						,      __lowercase			: Union[float, List[float]]						,      __lowercase			: Optional[Union[str, ChannelDimension]] = None						,      **__lowercase			: int						,      ):







            """simple docstring"""







            return normalize(__lowercase						,      mean=__lowercase						,      std=__lowercase						,      data_format=__lowercase						,      **__lowercase      )







       def 			snake_case   (							self			: Dict						,      __lowercase			: ImageInput						,      __lowercase			: Optional[bool] = None						,      __lowercase			: Optional[Dict[str, int]] = None						,      __lowercase			: Optional[bool] = None						,      __lowercase			: Optional[Dict[str, int]] = None						,      __lowercase			: PILImageResampling = None						,      __lowercase			: Optional[bool] = None						,      __lowercase			: Optional[float] = None						,      __lowercase			: Optional[bool] = None						,      __lowercase			: Optional[Union[float, List[float]]] = None						,      __lowercase			: Optional[Union[float, List[float]]] = None						,      __lowercase			: Optional[Union[str, TensorType]] = None						,      __lowercase			: ChannelDimension = ChannelDimension.FIRST						,      **__lowercase			: Optional[int]						,      ):







            """simple docstring"""







            __lowercase					=do_center_crop if do_center_crop is not None else self.do_center_crop
            __lowercase					=crop_size if crop_size is not None else self.crop_size
            __lowercase					=get_size_dict(__lowercase						,      param_name='crop_size'      )
            __lowercase					=do_resize if do_resize is not None else self.do_resize
            __lowercase					=size if size is not None else self.size
            __lowercase					=get_size_dict(__lowercase      )
            __lowercase					=resample if resample is not None else self.resample
            __lowercase					=do_rescale if do_rescale is not None else self.do_rescale
            __lowercase					=rescale_factor if rescale_factor is not None else self.rescale_factor
            __lowercase					=do_normalize if do_normalize is not None else self.do_normalize
            __lowercase					=image_mean if image_mean is not None else self.image_mean
            __lowercase					=image_std if image_std is not None else self.image_std

            __lowercase					=make_list_of_images(__lowercase      )

            if not valid_images(__lowercase      ):
                 raise ValueError(
                     'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
                     'torch.Tensor, tf.Tensor or jax.ndarray.'      )

            if do_center_crop and crop_size is None:
                 raise ValueError('If `do_center_crop` is set to `True`, `crop_size` must be provided.'      )

            if do_resize and size is None:
                 raise ValueError('Size must be specified if do_resize is True.'      )

            if do_rescale and rescale_factor is None:
                 raise ValueError('Rescale factor must be specified if do_rescale is True.'      )

            if do_normalize and (image_mean is None or image_std is None):
                 raise ValueError('Image mean and image standard deviation must be specified if do_normalize is True.'      )

            # All transformations expect numpy arrays.
            __lowercase					=[to_numpy_array(__lowercase      ) for image in images]

            if do_center_crop:
                 __lowercase					=[self.center_crop(__lowercase						,      __lowercase						,      size=__lowercase      ) for image in images]

            if do_resize:
                 __lowercase					=[self.resize(image=__lowercase						,      size=__lowercase						,      resample=__lowercase      ) for image in images]

            if do_rescale:
                 __lowercase					=[self.rescale(image=__lowercase						,      scale=__lowercase      ) for image in images]

            if do_normalize:
                 __lowercase					=[self.normalize(image=__lowercase						,      mean=__lowercase						,      std=__lowercase      ) for image in images]

            __lowercase					=[to_channel_dimension_format(__lowercase						,      __lowercase      ) for image in images]

            __lowercase					={'pixel_values': images}
            return BatchFeature(data=__lowercase						,      tensor_type=__lowercase      )


