






from typing import Dict, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    flip_channel_order,
    get_resize_output_image_size,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging


if is_vision_available():
	import PIL

if is_torch_available():
	import torch


lowerCamelCase : Any						   =       logging.get_logger(__name__)

class 		lowerCAmelCase     ( __a			):

					'''simple docstring'''

					_A						:			int									=      ['''pixel_values''']



					def __init__(  self				:	Tuple		,     __a				:	bool = True		,     __a				:	Dict[str, int] = None		,     __a				:	PILImageResampling = PILImageResampling.BILINEAR		,     __a				:	bool = True		,     __a				:	Union[int, float] = 1 / 255		,     __a				:	bool = True		,     __a				:	Dict[str, int] = None		,     __a				:	bool = True		,     **__a				:	Optional[int]		,     )			->  None:


												"""simple docstring"""

												super().__init__(**__a							)
												__lowercase      :							List[str]				=     size if size is not None else {"""shortest_edge""": 224}
												__lowercase      :							Dict				=     get_size_dict(__a		,     default_to_square=__a							)
												__lowercase      :							Any				=     crop_size if crop_size is not None else {"""height""": 256, """width""": 256}
												__lowercase      :							str				=     get_size_dict(__a		,     param_name="""crop_size"""							)

												__lowercase      :							Optional[Any]				=     do_resize
												__lowercase      :							int				=     size
												__lowercase      :							int				=     resample
												__lowercase      :							Union[str, Any]				=     do_rescale
												__lowercase      :							List[Any]				=     rescale_factor
												__lowercase      :							List[str]				=     do_center_crop
												__lowercase      :							Optional[int]				=     crop_size
												__lowercase      :							List[Any]				=     do_flip_channel_order



					def       lowerCAmelCase				(  self				:	Union[str, Any]		,     __a				:	np.ndarray		,     __a				:	Dict[str, int]		,     __a				:	PILImageResampling = PIL.Image.BILINEAR		,     __a				:	Optional[Union[str, ChannelDimension]] = None		,     **__a				:	int		,     )			->  np.ndarray:


												"""simple docstring"""

												__lowercase      :							Optional[Any]				=     get_size_dict(__a		,     default_to_square=__a							)
												if "shortest_edge" not in size:
																			raise ValueError(F"The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}"							)
												__lowercase      :							List[Any]				=     get_resize_output_image_size(__a		,     size=size["""shortest_edge"""]		,     default_to_square=__a							)
												return resize(__a		,     size=__a		,     resample=__a		,     data_format=__a		,     **__a							)



					def       lowerCAmelCase				(  self				:	Optional[Any]		,     __a				:	np.ndarray		,     __a				:	Dict[str, int]		,     __a				:	Optional[Union[str, ChannelDimension]] = None		,     **__a				:	Dict		,     )			->  np.ndarray:


												"""simple docstring"""

												__lowercase      :							Optional[int]				=     get_size_dict(__a							)
												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 center_crop(__a		,     size=(size["""height"""], size["""width"""])		,     data_format=__a		,     **__a							)



					def       lowerCAmelCase				(  self				:	Optional[Any]		,     __a				:	np.ndarray		,     __a				:	Union[int, float]		,     __a				:	Optional[Union[str, ChannelDimension]] = None		,     **__a				:	Any		,     )			->  Union[str, Any]:


												"""simple docstring"""

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



					def       lowerCAmelCase				(  self				:	Optional[Any]		,     __a				:	np.ndarray		,     __a				:	Optional[Union[str, ChannelDimension]] = None							)			->  np.ndarray:


												"""simple docstring"""

												return flip_channel_order(__a		,     data_format=__a							)



					def       lowerCAmelCase				(  self				:	Any		,     __a				:	ImageInput		,     __a				:	bool = None		,     __a				:	Dict[str, int] = None		,     __a				:	PILImageResampling = None		,     __a				:	bool = None		,     __a				:	float = None		,     __a				:	bool = None		,     __a				:	Dict[str, int] = None		,     __a				:	bool = None		,     __a				:	Optional[Union[str, TensorType]] = None		,     __a				:	ChannelDimension = ChannelDimension.FIRST		,     **__a				:	str		,     )			->  PIL.Image.Image:


												"""simple docstring"""

												__lowercase      :							Optional[int]				=     do_resize if do_resize is not None else self.do_resize
												__lowercase      :							str				=     resample if resample is not None else self.resample
												__lowercase      :							int				=     do_rescale if do_rescale is not None else self.do_rescale
												__lowercase      :							int				=     rescale_factor if rescale_factor is not None else self.rescale_factor
												__lowercase      :							Union[str, Any]				=     do_center_crop if do_center_crop is not None else self.do_center_crop
												__lowercase      :							Optional[int]				=     (
												    do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order
												)

												__lowercase      :							Optional[Any]				=     size if size is not None else self.size
												__lowercase      :							List[Any]				=     get_size_dict(__a		,     default_to_square=__a							)
												__lowercase      :							List[str]				=     crop_size if crop_size is not None else self.crop_size
												__lowercase      :							List[str]				=     get_size_dict(__a		,     param_name="""crop_size"""							)

												__lowercase      :							Union[str, Any]				=     make_list_of_images(__a							)

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

												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_center_crop and crop_size is None:
																			raise ValueError("""Crop size must be specified if do_center_crop is True."""							)

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

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

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

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

												# the pretrained checkpoints assume images are BGR, not RGB
												if do_flip_channel_order:
																			__lowercase      :							Any				=     [self.flip_channel_order(image=__a							) for image in images]

												__lowercase      :							List[str]				=     [to_channel_dimension_format(__a		,     __a							) for image in images]

												__lowercase      :							Tuple				=     {"""pixel_values""": images}
												return BatchFeature(data=__a		,     tensor_type=__a							)



					def       lowerCAmelCase				(  self				:	Any		,     __a				:	str		,     __a				:	List[Tuple] = None							)			->  Dict:


												"""simple docstring"""

												__lowercase      :							str				=     outputs.logits

												# Resize logits and compute semantic segmentation maps
												if target_sizes is not None:
																			if len(__a							) != len(__a							):
																										raise ValueError(
																										    """Make sure that you pass in as many target sizes as the batch dimension of the logits"""							)

																			if is_torch_tensor(__a							):
																										__lowercase      :							List[Any]				=     target_sizes.numpy()

																			__lowercase      :							Dict				=     []

																			for idx in range(len(__a							)							):
																										__lowercase      :							Optional[int]				=     torch.nn.functional.interpolate(
																										    logits[idx].unsqueeze(dim=0							)		,     size=target_sizes[idx]		,     mode="""bilinear"""		,     align_corners=__a							)
																										__lowercase      :							Union[str, Any]				=     resized_logits[0].argmax(dim=0							)
																										semantic_segmentation.append(__a							)
												else:
																			__lowercase      :							Dict				=     logits.argmax(dim=1							)
																			__lowercase      :							Any				=     [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]							)]

												return semantic_segmentation







lowerCamelCase : List[str]						   =       '''0.18.2'''

from .configuration_utils import ConfigMixin
from .utils import (
    OptionalDependencyNotAvailable,
    is_flax_available,
    is_inflect_available,
    is_invisible_watermark_available,
    is_k_diffusion_available,
    is_k_diffusion_version,
    is_librosa_available,
    is_note_seq_available,
    is_onnx_available,
    is_scipy_available,
    is_torch_available,
    is_torchsde_available,
    is_transformers_available,
    is_transformers_version,
    is_unidecode_available,
    logging,
)


try:
	if not is_onnx_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_onnx_objects import *  # noqa F403
else:
	from .pipelines import OnnxRuntimeModel

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_pt_objects import *  # noqa F403
else:
	from .models import (
	    AutoencoderKL,
	    ControlNetModel,
	    ModelMixin,
	    PriorTransformer,
	    TaFilmDecoder,
	    TransformeraDModel,
	    UNetaDModel,
	    UNetaDConditionModel,
	    UNetaDModel,
	    UNetaDConditionModel,
	    VQModel,
	)
	from .optimization import (
	    get_constant_schedule,
	    get_constant_schedule_with_warmup,
	    get_cosine_schedule_with_warmup,
	    get_cosine_with_hard_restarts_schedule_with_warmup,
	    get_linear_schedule_with_warmup,
	    get_polynomial_decay_schedule_with_warmup,
	    get_scheduler,
	)
	from .pipelines import (
	    AudioPipelineOutput,
	    ConsistencyModelPipeline,
	    DanceDiffusionPipeline,
	    DDIMPipeline,
	    DDPMPipeline,
	    DiffusionPipeline,
	    DiTPipeline,
	    ImagePipelineOutput,
	    KarrasVePipeline,
	    LDMPipeline,
	    LDMSuperResolutionPipeline,
	    PNDMPipeline,
	    RePaintPipeline,
	    ScoreSdeVePipeline,
	)
	from .schedulers import (
	    CMStochasticIterativeScheduler,
	    DDIMInverseScheduler,
	    DDIMParallelScheduler,
	    DDIMScheduler,
	    DDPMParallelScheduler,
	    DDPMScheduler,
	    DEISMultistepScheduler,
	    DPMSolverMultistepInverseScheduler,
	    DPMSolverMultistepScheduler,
	    DPMSolverSinglestepScheduler,
	    EulerAncestralDiscreteScheduler,
	    EulerDiscreteScheduler,
	    HeunDiscreteScheduler,
	    IPNDMScheduler,
	    KarrasVeScheduler,
	    KDPMaAncestralDiscreteScheduler,
	    KDPMaDiscreteScheduler,
	    PNDMScheduler,
	    RePaintScheduler,
	    SchedulerMixin,
	    ScoreSdeVeScheduler,
	    UnCLIPScheduler,
	    UniPCMultistepScheduler,
	    VQDiffusionScheduler,
	)
	from .training_utils import EMAModel

try:
	if not (is_torch_available() and is_scipy_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_torch_and_scipy_objects import *  # noqa F403
else:
	from .schedulers import LMSDiscreteScheduler

try:
	if not (is_torch_available() and is_torchsde_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_torch_and_torchsde_objects import *  # noqa F403
else:
	from .schedulers import DPMSolverSDEScheduler

try:
	if not (is_torch_available() and is_transformers_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_torch_and_transformers_objects import *  # noqa F403
else:
	from .pipelines import (
	    AltDiffusionImgaImgPipeline,
	    AltDiffusionPipeline,
	    AudioLDMPipeline,
	    CycleDiffusionPipeline,
	    IFImgaImgPipeline,
	    IFImgaImgSuperResolutionPipeline,
	    IFInpaintingPipeline,
	    IFInpaintingSuperResolutionPipeline,
	    IFPipeline,
	    IFSuperResolutionPipeline,
	    ImageTextPipelineOutput,
	    KandinskyImgaImgPipeline,
	    KandinskyInpaintPipeline,
	    KandinskyPipeline,
	    KandinskyPriorPipeline,
	    KandinskyVaaControlnetImgaImgPipeline,
	    KandinskyVaaControlnetPipeline,
	    KandinskyVaaImgaImgPipeline,
	    KandinskyVaaInpaintPipeline,
	    KandinskyVaaPipeline,
	    KandinskyVaaPriorEmbaEmbPipeline,
	    KandinskyVaaPriorPipeline,
	    LDMTextToImagePipeline,
	    PaintByExamplePipeline,
	    SemanticStableDiffusionPipeline,
	    ShapEImgaImgPipeline,
	    ShapEPipeline,
	    StableDiffusionAttendAndExcitePipeline,
	    StableDiffusionControlNetImgaImgPipeline,
	    StableDiffusionControlNetInpaintPipeline,
	    StableDiffusionControlNetPipeline,
	    StableDiffusionDepthaImgPipeline,
	    StableDiffusionDiffEditPipeline,
	    StableDiffusionImageVariationPipeline,
	    StableDiffusionImgaImgPipeline,
	    StableDiffusionInpaintPipeline,
	    StableDiffusionInpaintPipelineLegacy,
	    StableDiffusionInstructPixaPixPipeline,
	    StableDiffusionLatentUpscalePipeline,
	    StableDiffusionLDMaDPipeline,
	    StableDiffusionModelEditingPipeline,
	    StableDiffusionPanoramaPipeline,
	    StableDiffusionParadigmsPipeline,
	    StableDiffusionPipeline,
	    StableDiffusionPipelineSafe,
	    StableDiffusionPixaPixZeroPipeline,
	    StableDiffusionSAGPipeline,
	    StableDiffusionUpscalePipeline,
	    StableUnCLIPImgaImgPipeline,
	    StableUnCLIPPipeline,
	    TextToVideoSDPipeline,
	    TextToVideoZeroPipeline,
	    UnCLIPImageVariationPipeline,
	    UnCLIPPipeline,
	    UniDiffuserModel,
	    UniDiffuserPipeline,
	    UniDiffuserTextDecoder,
	    VersatileDiffusionDualGuidedPipeline,
	    VersatileDiffusionImageVariationPipeline,
	    VersatileDiffusionPipeline,
	    VersatileDiffusionTextToImagePipeline,
	    VideoToVideoSDPipeline,
	    VQDiffusionPipeline,
	)

try:
	if not (is_torch_available() and is_transformers_available() and is_invisible_watermark_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_torch_and_transformers_and_invisible_watermark_objects import *  # noqa F403
else:
	from .pipelines import StableDiffusionXLImgaImgPipeline, StableDiffusionXLPipeline

try:
	if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import *  # noqa F403
else:
	from .pipelines import StableDiffusionKDiffusionPipeline

try:
	if not (is_torch_available() and is_transformers_available() and is_onnx_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_torch_and_transformers_and_onnx_objects import *  # noqa F403
else:
	from .pipelines import (
	    OnnxStableDiffusionImgaImgPipeline,
	    OnnxStableDiffusionInpaintPipeline,
	    OnnxStableDiffusionInpaintPipelineLegacy,
	    OnnxStableDiffusionPipeline,
	    OnnxStableDiffusionUpscalePipeline,
	    StableDiffusionOnnxPipeline,
	)

try:
	if not (is_torch_available() and is_librosa_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_torch_and_librosa_objects import *  # noqa F403
else:
	from .pipelines import AudioDiffusionPipeline, Mel

try:
	if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_transformers_and_torch_and_note_seq_objects import *  # noqa F403
else:
	from .pipelines import SpectrogramDiffusionPipeline

try:
	if not is_flax_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_flax_objects import *  # noqa F403
else:
	from .models.controlnet_flax import FlaxControlNetModel
	from .models.modeling_flax_utils import FlaxModelMixin
	from .models.unet_ad_condition_flax import FlaxUNetaDConditionModel
	from .models.vae_flax import FlaxAutoencoderKL
	from .pipelines import FlaxDiffusionPipeline
	from .schedulers import (
	    FlaxDDIMScheduler,
	    FlaxDDPMScheduler,
	    FlaxDPMSolverMultistepScheduler,
	    FlaxKarrasVeScheduler,
	    FlaxLMSDiscreteScheduler,
	    FlaxPNDMScheduler,
	    FlaxSchedulerMixin,
	    FlaxScoreSdeVeScheduler,
	)


try:
	if not (is_flax_available() and is_transformers_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_flax_and_transformers_objects import *  # noqa F403
else:
	from .pipelines import (
	    FlaxStableDiffusionControlNetPipeline,
	    FlaxStableDiffusionImgaImgPipeline,
	    FlaxStableDiffusionInpaintPipeline,
	    FlaxStableDiffusionPipeline,
	)

try:
	if not (is_note_seq_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_note_seq_objects import *  # noqa F403
else:
	from .pipelines import MidiProcessor