




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


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






class      UpperCamelCase_  (a__  ):







						"""simple docstring"""


						_lowerCAmelCase         =       ['safety_checker', 'feature_extractor']







						def __init__(  self   :							str				,			_lowerCamelCase   :							AutoencoderKL				,			_lowerCamelCase   :							CLIPTextModel				,			_lowerCamelCase   :							CLIPTokenizer				,			_lowerCamelCase   :							UNetaDConditionModel				,			_lowerCamelCase   :							Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]				,			_lowerCamelCase   :							StableDiffusionSafetyChecker				,			_lowerCamelCase   :							CLIPImageProcessor				,			_lowerCamelCase   :							bool = True				,			):





											"""simple docstring"""







											super().__init__()
											if hasattr(scheduler.config				,			'''steps_offset'''     ) and scheduler.config.steps_offset != 1:
																A_			:  int			=				(
																    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'''				,			_lowerCamelCase				,			standard_warn=_lowerCamelCase     )
																A_			:  List[str]			=				dict(scheduler.config     )
																A_			:  List[Any]			=				1
																A_			:  Tuple			=				FrozenDict(_lowerCamelCase     )

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







						@property
						def    _a     (  self   :							Tuple     ):





											"""simple docstring"""







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







						def    _a     (  self   :							Optional[Any]				,			_lowerCamelCase   :							Optional[Union[str, int]] = "auto"     ):





											"""simple docstring"""







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







						def    _a     (  self   :							Union[str, Any]     ):





											"""simple docstring"""







											self.enable_attention_slicing(_lowerCamelCase     )







						@torch.no_grad()
						def    _a     (  self   :							Tuple				,			_lowerCamelCase   :							Union[str, List[str]]				,			_lowerCamelCase   :							Union[torch.FloatTensor, PIL.Image.Image]				,			_lowerCamelCase   :							Union[torch.FloatTensor, PIL.Image.Image]				,			_lowerCamelCase   :							float = 0.8				,			_lowerCamelCase   :							Optional[int] = 50				,			_lowerCamelCase   :							Optional[float] = 7.5				,			_lowerCamelCase   :							Optional[Union[str, List[str]]] = None				,			_lowerCamelCase   :							Optional[int] = 1				,			_lowerCamelCase   :							Optional[float] = 0.0				,			_lowerCamelCase   :							Optional[torch.Generator] = None				,			_lowerCamelCase   :							Optional[str] = "pil"				,			_lowerCamelCase   :							bool = True				,			_lowerCamelCase   :							Optional[Callable[[int, int, torch.FloatTensor], None]] = None				,			_lowerCamelCase   :							int = 1				,			):





											"""simple docstring"""







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







						@torch.no_grad()
						def    _a     (  self   :							Any				,			_lowerCamelCase   :							Union[str, List[str]]				,			_lowerCamelCase   :							Union[torch.FloatTensor, PIL.Image.Image]				,			_lowerCamelCase   :							float = 0.8				,			_lowerCamelCase   :							Optional[int] = 50				,			_lowerCamelCase   :							Optional[float] = 7.5				,			_lowerCamelCase   :							Optional[Union[str, List[str]]] = None				,			_lowerCamelCase   :							Optional[int] = 1				,			_lowerCamelCase   :							Optional[float] = 0.0				,			_lowerCamelCase   :							Optional[torch.Generator] = None				,			_lowerCamelCase   :							Optional[str] = "pil"				,			_lowerCamelCase   :							bool = True				,			_lowerCamelCase   :							Optional[Callable[[int, int, torch.FloatTensor], None]] = None				,			_lowerCamelCase   :							int = 1				,			**_lowerCamelCase   :							int				,			):





											"""simple docstring"""







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







						@torch.no_grad()
						def    _a     (  self   :							Optional[int]				,			_lowerCamelCase   :							Union[str, List[str]]				,			_lowerCamelCase   :							int = 512				,			_lowerCamelCase   :							int = 512				,			_lowerCamelCase   :							int = 50				,			_lowerCamelCase   :							float = 7.5				,			_lowerCamelCase   :							Optional[Union[str, List[str]]] = None				,			_lowerCamelCase   :							Optional[int] = 1				,			_lowerCamelCase   :							float = 0.0				,			_lowerCamelCase   :							Optional[torch.Generator] = None				,			_lowerCamelCase   :							Optional[torch.FloatTensor] = None				,			_lowerCamelCase   :							Optional[str] = "pil"				,			_lowerCamelCase   :							bool = True				,			_lowerCamelCase   :							Optional[Callable[[int, int, torch.FloatTensor], None]] = None				,			_lowerCamelCase   :							int = 1				,			):





											"""simple docstring"""







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









'''simple docstring'''




import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
							import torch

if is_vision_available():
							from PIL import Image

							from transformers import SwinaSRImageProcessor
							from transformers.image_transforms import get_image_size






class      UpperCamelCase_  (unittest.TestCase  ):







						"""simple docstring"""


						def __init__(  self   :							Tuple				,			_lowerCamelCase   :							str				,			_lowerCamelCase   :							str=7				,			_lowerCamelCase   :							Tuple=3				,			_lowerCamelCase   :							Any=18				,			_lowerCamelCase   :							Optional[int]=30				,			_lowerCamelCase   :							List[Any]=400				,			_lowerCamelCase   :							int=True				,			_lowerCamelCase   :							Dict=1 / 255				,			_lowerCamelCase   :							List[str]=True				,			_lowerCamelCase   :							Optional[int]=8				,			):





											"""simple docstring"""







											A_			:  Tuple			=				parent
											A_			:  str			=				batch_size
											A_			:  Optional[Any]			=				num_channels
											A_			:  Union[str, Any]			=				image_size
											A_			:  Optional[int]			=				min_resolution
											A_			:  List[Any]			=				max_resolution
											A_			:  int			=				do_rescale
											A_			:  Optional[Any]			=				rescale_factor
											A_			:  Any			=				do_pad
											A_			:  Tuple			=				pad_size







						def    _a     (  self   :							List[Any]     ):





											"""simple docstring"""







											return {
											    "do_rescale": self.do_rescale,
											    "rescale_factor": self.rescale_factor,
											    "do_pad": self.do_pad,
											    "pad_size": self.pad_size,
											}







						def    _a     (  self   :							Tuple				,			_lowerCamelCase   :							List[str]=False				,			_lowerCamelCase   :							Tuple=False				,			_lowerCamelCase   :							str=False     ):





											"""simple docstring"""







											assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

											if equal_resolution:
																A_			:  List[Any]			=				[]
																for i in range(self.batch_size     ):
																					image_inputs.append(
																					    np.random.randint(
																					        255				,			size=(self.num_channels, self.max_resolution, self.max_resolution)				,			dtype=np.uinta     )     )
											else:
																A_			:  List[Any]			=				[]
																for i in range(self.batch_size     ):
																					A_			,A_			:  List[str]			=				np.random.choice(np.arange(self.min_resolution				,			self.max_resolution     )				,			2     )
																					image_inputs.append(np.random.randint(255				,			size=(self.num_channels, width, height)				,			dtype=np.uinta     )     )

											if not numpify and not torchify:
																# PIL expects the channel dimension as last dimension
																A_			:  Any			=				[Image.fromarray(np.moveaxis(_lowerCamelCase				,			0				,			-1     )     ) for x in image_inputs]

											if torchify:
																A_			:  str			=				[torch.from_numpy(_lowerCamelCase     ) for x in image_inputs]

											return image_inputs






@require_torch
@require_vision
class      UpperCamelCase_  (a__,   unittest.TestCase  ):







						"""simple docstring"""


						_lowerCAmelCase         =       SwinaSRImageProcessor if is_vision_available() else None







						def    _a     (  self   :							List[str]     ):





											"""simple docstring"""







											A_			:  int			=				SwinaSRImageProcessingTester(self     )







						@property
						def    _a     (  self   :							Union[str, Any]     ):





											"""simple docstring"""







											return self.image_processor_tester.prepare_image_processor_dict()







						def    _a     (  self   :							Any     ):





											"""simple docstring"""







											A_			:  Optional[int]			=				self.image_processing_class(**self.image_processor_dict     )
											self.assertTrue(hasattr(_lowerCamelCase				,			'''do_rescale'''     )     )
											self.assertTrue(hasattr(_lowerCamelCase				,			'''rescale_factor'''     )     )
											self.assertTrue(hasattr(_lowerCamelCase				,			'''do_pad'''     )     )
											self.assertTrue(hasattr(_lowerCamelCase				,			'''pad_size'''     )     )







						def    _a     (  self   :							Tuple     ):





											"""simple docstring"""







											pass







						def    _a     (  self   :							Optional[int]				,			_lowerCamelCase   :							Optional[int]     ):





											"""simple docstring"""







											A_			,A_			:  Any			=				get_image_size(_lowerCamelCase     )
											A_			:  List[Any]			=				self.image_processor_tester.pad_size

											A_			:  Dict			=				(old_height // size + 1) * size - old_height
											A_			:  Optional[Any]			=				(old_width // size + 1) * size - old_width
											return old_height + pad_height, old_width + pad_width







						def    _a     (  self   :							int     ):





											"""simple docstring"""







											A_			:  Dict			=				self.image_processing_class(**self.image_processor_dict     )
											# create random PIL images
											A_			:  Optional[int]			=				self.image_processor_tester.prepare_inputs(equal_resolution=_lowerCamelCase     )
											for image in image_inputs:
																self.assertIsInstance(_lowerCamelCase				,			Image.Image     )

											# Test not batched input
											A_			:  Any			=				image_processor(image_inputs[0]				,			return_tensors='''pt'''     ).pixel_values
											A_			,A_			:  List[Any]			=				self.calculate_expected_size(np.array(image_inputs[0]     )     )
											self.assertEqual(
											    encoded_images.shape				,			(
											        1,
											        self.image_processor_tester.num_channels,
											        expected_height,
											        expected_width,
											    )				,			)







						def    _a     (  self   :							Optional[Any]     ):





											"""simple docstring"""







											A_			:  Optional[Any]			=				self.image_processing_class(**self.image_processor_dict     )
											# create random numpy tensors
											A_			:  Dict			=				self.image_processor_tester.prepare_inputs(equal_resolution=_lowerCamelCase				,			numpify=_lowerCamelCase     )
											for image in image_inputs:
																self.assertIsInstance(_lowerCamelCase				,			np.ndarray     )

											# Test not batched input
											A_			:  Union[str, Any]			=				image_processor(image_inputs[0]				,			return_tensors='''pt'''     ).pixel_values
											A_			,A_			:  Union[str, Any]			=				self.calculate_expected_size(image_inputs[0]     )
											self.assertEqual(
											    encoded_images.shape				,			(
											        1,
											        self.image_processor_tester.num_channels,
											        expected_height,
											        expected_width,
											    )				,			)







						def    _a     (  self   :							int     ):





											"""simple docstring"""







											A_			:  Union[str, Any]			=				self.image_processing_class(**self.image_processor_dict     )
											# create random PyTorch tensors
											A_			:  List[Any]			=				self.image_processor_tester.prepare_inputs(equal_resolution=_lowerCamelCase				,			torchify=_lowerCamelCase     )
											for image in image_inputs:
																self.assertIsInstance(_lowerCamelCase				,			torch.Tensor     )

											# Test not batched input
											A_			:  int			=				image_processor(image_inputs[0]				,			return_tensors='''pt'''     ).pixel_values
											A_			,A_			:  str			=				self.calculate_expected_size(image_inputs[0]     )
											self.assertEqual(
											    encoded_images.shape				,			(
											        1,
											        self.image_processor_tester.num_channels,
											        expected_height,
											        expected_width,
											    )				,			)



