



"""simple docstring"""






import io
import math
from typing import Dict, Optional, Union

import numpy as np
from huggingface_hub import hf_hub_download

from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    get_image_size,
    infer_channel_dimension_format,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_vision_available, logging
from ...utils.import_utils import requires_backends


if is_vision_available():
   import textwrap

   from PIL import Image, ImageDraw, ImageFont

if is_torch_available():
   import torch

   from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
   lowerCAmelCase__              =							False


lowerCAmelCase__              =							logging.get_logger(__name__)
lowerCAmelCase__              =							'''ybelkada/fonts'''






def 			snake_case_    ( ):


       '''simple docstring'''





       if is_torch_available() and not is_torch_greater_or_equal_than_1_11:
              raise ImportError(
                  F'''You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use '''
                  '''Pix2StructImageProcessor. Please upgrade torch.'''		)






def 			snake_case_    ( A_   :						Tuple,							A_   :						List[Any],							A_   :						Union[str, Any]		):


       '''simple docstring'''





       requires_backends(A_,							['''torch''']		)
       _check_torch_version()

       _lowerCamelCase		:							Optional[Any]            =					image_tensor.unsqueeze(0		)
       _lowerCamelCase		:							Optional[Any]            =					torch.nn.functional.unfold(A_,							(patch_height, patch_width),							stride=(patch_height, patch_width)		)
       _lowerCamelCase		:							Tuple            =					patches.reshape(image_tensor.size(0		),							image_tensor.size(1		),							A_,							A_,							-1		)
       _lowerCamelCase		:							str            =					patches.permute(0,							4,							2,							3,							1		).reshape(
           image_tensor.size(2		) // patch_height,							image_tensor.size(3		) // patch_width,							image_tensor.size(1		) * patch_height * patch_width,							)
       return patches.unsqueeze(0		)






def 			snake_case_    ( A_   :						str,							A_   :						int = 36,							A_   :						str = "black",							A_   :						str = "white",							A_   :						int = 5,							A_   :						int = 5,							A_   :						int = 5,							A_   :						int = 5,							A_   :						Optional[bytes] = None,							A_   :						Optional[str] = None,							):


       '''simple docstring'''





       requires_backends(A_,							'''vision'''		)
       # Add new lines so that each line is no more than 80 characters.

       _lowerCamelCase		:							Optional[Any]            =					textwrap.TextWrapper(width=80		)
       _lowerCamelCase		:							int            =					wrapper.wrap(text=A_		)
       _lowerCamelCase		:							List[Any]            =					'''\n'''.join(A_		)

       if font_bytes is not None and font_path is None:
              _lowerCamelCase		:							Optional[int]            =					io.BytesIO(A_		)
       elif font_path is not None:
              _lowerCamelCase		:							Union[str, Any]            =					font_path
       else:
              _lowerCamelCase		:							str            =					hf_hub_download(A_,							'''Arial.TTF'''		)
       _lowerCamelCase		:							Optional[Any]            =					ImageFont.truetype(A_,							encoding='''UTF-8''',							size=A_		)

       # Use a temporary canvas to determine the width and height in pixels when
       # rendering the text.
       _lowerCamelCase		:							Union[str, Any]            =					ImageDraw.Draw(Image.new('''RGB''',							(1, 1),							A_		)		)
       _lowerCamelCase     ,       _lowerCamelCase     ,       _lowerCamelCase     ,       _lowerCamelCase		:							List[Any]            =					temp_draw.textbbox((0, 0),							A_,							A_		)

       # Create the actual image with a bit of padding around the text.
       _lowerCamelCase		:							int            =					text_width + left_padding + right_padding
       _lowerCamelCase		:							Dict            =					text_height + top_padding + bottom_padding
       _lowerCamelCase		:							int            =					Image.new('''RGB''',							(image_width, image_height),							A_		)
       _lowerCamelCase		:							Optional[Any]            =					ImageDraw.Draw(A_		)
       draw.text(xy=(left_padding, top_padding),							text=A_,							fill=A_,							font=A_		)
       return image






def 			snake_case_    ( A_   :						np.ndarray,							A_   :						str,							**A_   :						Optional[int]		):


       '''simple docstring'''





       requires_backends(A_,							'''vision'''		)

       # Convert to PIL image if necessary
       _lowerCamelCase		:							List[str]            =					to_pil_image(A_		)

       _lowerCamelCase		:							Union[str, Any]            =					render_text(A_,							**A_		)
       _lowerCamelCase		:							int            =					max(header_image.width,							image.width		)

       _lowerCamelCase		:							List[Any]            =					int(image.height * (new_width / image.width)		)
       _lowerCamelCase		:							Dict            =					int(header_image.height * (new_width / header_image.width)		)

       _lowerCamelCase		:							List[Any]            =					Image.new('''RGB''',							(new_width, new_height + new_header_height),							'''white'''		)
       new_image.paste(header_image.resize((new_width, new_header_height)		),							(0, 0)		)
       new_image.paste(image.resize((new_width, new_height)		),							(0, new_header_height)		)

       # Convert back to the original framework if necessary
       _lowerCamelCase		:							Optional[int]            =					to_numpy_array(A_		)

       if infer_channel_dimension_format(A_		) == ChannelDimension.LAST:
              _lowerCamelCase		:							int            =					to_channel_dimension_format(A_,							ChannelDimension.LAST		)

       return new_image







class 			__snake_case			(      _lowercase):
  snake_case__							:  str         =		["flattened_patches"]




  def __init__(					self	:		str		,   __lowerCAmelCase	:		bool = True		,   __lowerCAmelCase	:		bool = True		,   __lowerCAmelCase	:		Dict[str, int] = None		,   __lowerCAmelCase	:		int = 2_0_4_8		,   __lowerCAmelCase	:		bool = False		,   **__lowerCAmelCase	:		Optional[int]		,   ):






         """simple docstring"""






         super().__init__(**__lowerCAmelCase						)
         _lowerCamelCase		:							Union[str, Any]            =					patch_size if patch_size is not None else {'''height''': 1_6, '''width''': 1_6}
         _lowerCamelCase		:							List[str]            =					do_normalize
         _lowerCamelCase		:							Dict            =					do_convert_rgb
         _lowerCamelCase		:							Union[str, Any]            =					max_patches
         _lowerCamelCase		:							Any            =					is_vqa




  def 		SCREAMING_SNAKE_CASE							(					self	:		Any		,   __lowerCAmelCase	:		np.ndarray		,   __lowerCAmelCase	:		int		,   __lowerCAmelCase	:		dict		,   **__lowerCAmelCase	:		Union[str, Any]						):






         """simple docstring"""






         requires_backends(self.extract_flattened_patches		,   '''torch'''						)
         _check_torch_version()

         # convert to torch
         _lowerCamelCase		:							Any            =					to_channel_dimension_format(__lowerCAmelCase		,   ChannelDimension.FIRST						)
         _lowerCamelCase		:							int            =					torch.from_numpy(__lowerCAmelCase						)

         _lowerCamelCase     ,       _lowerCamelCase		:							Union[str, Any]            =					patch_size['''height'''], patch_size['''width''']
         _lowerCamelCase     ,       _lowerCamelCase		:							Dict            =					get_image_size(__lowerCAmelCase						)

         # maximize scale s.t.
         _lowerCamelCase		:							Any            =					math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width)						)
         _lowerCamelCase		:							str            =					max(min(math.floor(scale * image_height / patch_height						)		,   __lowerCAmelCase						)		,   1						)
         _lowerCamelCase		:							Optional[int]            =					max(min(math.floor(scale * image_width / patch_width						)		,   __lowerCAmelCase						)		,   1						)
         _lowerCamelCase		:							List[Any]            =					max(num_feasible_rows * patch_height		,   1						)
         _lowerCamelCase		:							str            =					max(num_feasible_cols * patch_width		,   1						)

         _lowerCamelCase		:							Optional[Any]            =					torch.nn.functional.interpolate(
             image.unsqueeze(0						)		,   size=(resized_height, resized_width)		,   mode='''bilinear'''		,   align_corners=__lowerCAmelCase		,   antialias=__lowerCAmelCase		,   ).squeeze(0						)

         # [1, rows, columns, patch_height * patch_width * image_channels]
         _lowerCamelCase		:							int            =					torch_extract_patches(__lowerCAmelCase		,   __lowerCAmelCase		,   __lowerCAmelCase						)

         _lowerCamelCase		:							Optional[int]            =					patches.shape
         _lowerCamelCase		:							int            =					patches_shape[1]
         _lowerCamelCase		:							Union[str, Any]            =					patches_shape[2]
         _lowerCamelCase		:							Optional[int]            =					patches_shape[3]

         # [rows * columns, patch_height * patch_width * image_channels]
         _lowerCamelCase		:							List[Any]            =					patches.reshape([rows * columns, depth]						)

         # [rows * columns, 1]
         _lowerCamelCase		:							List[Any]            =					torch.arange(__lowerCAmelCase						).reshape([rows, 1]						).repeat(1		,   __lowerCAmelCase						).reshape([rows * columns, 1]						)
         _lowerCamelCase		:							Any            =					torch.arange(__lowerCAmelCase						).reshape([1, columns]						).repeat(__lowerCAmelCase		,   1						).reshape([rows * columns, 1]						)

         # Offset by 1 so the ids do not contain zeros, which represent padding.
         row_ids += 1
         col_ids += 1

         # Prepare additional patch features.
         # [rows * columns, 1]
         _lowerCamelCase		:							int            =					row_ids.to(torch.floataa						)
         _lowerCamelCase		:							str            =					col_ids.to(torch.floataa						)

         # [rows * columns, 2 + patch_height * patch_width * image_channels]
         _lowerCamelCase		:							Any            =					torch.cat([row_ids, col_ids, patches]		,   -1						)

         # [max_patches, 2 + patch_height * patch_width * image_channels]
         _lowerCamelCase		:							Any            =					torch.nn.functional.pad(__lowerCAmelCase		,   [0, 0, 0, max_patches - (rows * columns)]						).float()

         _lowerCamelCase		:							Any            =					to_numpy_array(__lowerCAmelCase						)

         return result




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






         """simple docstring"""






         if image.dtype == np.uinta:
                _lowerCamelCase		:							Tuple            =					image.astype(np.floataa						)

         # take mean across the whole `image`
         _lowerCamelCase		:							List[str]            =					np.mean(__lowerCAmelCase						)
         _lowerCamelCase		:							Dict            =					np.std(__lowerCAmelCase						)
         _lowerCamelCase		:							Tuple            =					max(__lowerCAmelCase		,   1.0 / math.sqrt(np.prod(image.shape						)						)						)

         return normalize(__lowerCAmelCase		,   mean=__lowerCAmelCase		,   std=__lowerCAmelCase		,   **__lowerCAmelCase						)




  def 		SCREAMING_SNAKE_CASE							(					self	:		str		,   __lowerCAmelCase	:		ImageInput		,   __lowerCAmelCase	:		Optional[str] = None		,   __lowerCAmelCase	:		bool = None		,   __lowerCAmelCase	:		Optional[bool] = None		,   __lowerCAmelCase	:		Optional[int] = None		,   __lowerCAmelCase	:		Optional[Dict[str, int]] = None		,   __lowerCAmelCase	:		Optional[Union[str, TensorType]] = None		,   __lowerCAmelCase	:		ChannelDimension = ChannelDimension.FIRST		,   **__lowerCAmelCase	:		Any		,   ):






         """simple docstring"""






         _lowerCamelCase		:							Optional[Any]            =					do_normalize if do_normalize is not None else self.do_normalize
         _lowerCamelCase		:							Tuple            =					do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
         _lowerCamelCase		:							str            =					patch_size if patch_size is not None else self.patch_size
         _lowerCamelCase		:							List[Any]            =					max_patches if max_patches is not None else self.max_patches
         _lowerCamelCase		:							Any            =					self.is_vqa

         if kwargs.get('''data_format'''		,   __lowerCAmelCase						) is not None:
                raise ValueError('''data_format is not an accepted input as the outputs are '''						)

         _lowerCamelCase		:							Tuple            =					make_list_of_images(__lowerCAmelCase						)

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

         # PIL RGBA images are converted to RGB
         if do_convert_rgb:
                _lowerCamelCase		:							Optional[Any]            =					[convert_to_rgb(__lowerCAmelCase						) for image in images]

         # All transformations expect numpy arrays.
         _lowerCamelCase		:							Optional[Any]            =					[to_numpy_array(__lowerCAmelCase						) for image in images]

         if is_vqa:
                if header_text is None:
                       raise ValueError('''A header text must be provided for VQA models.'''						)
                _lowerCamelCase		:							str            =					kwargs.pop('''font_bytes'''		,   __lowerCAmelCase						)
                _lowerCamelCase		:							int            =					kwargs.pop('''font_path'''		,   __lowerCAmelCase						)

                if isinstance(__lowerCAmelCase		,   __lowerCAmelCase						):
                       _lowerCamelCase		:							Optional[Any]            =					[header_text] * len(__lowerCAmelCase						)

                _lowerCamelCase		:							Dict            =					[
                    render_header(__lowerCAmelCase		,   header_text[i]		,   font_bytes=__lowerCAmelCase		,   font_path=__lowerCAmelCase						)
                    for i, image in enumerate(__lowerCAmelCase						)
                ]

         if do_normalize:
                _lowerCamelCase		:							Dict            =					[self.normalize(image=__lowerCAmelCase						) for image in images]

         # convert to torch tensor and permute
         _lowerCamelCase		:							Optional[int]            =					[
             self.extract_flattened_patches(image=__lowerCAmelCase		,   max_patches=__lowerCAmelCase		,   patch_size=__lowerCAmelCase						)
             for image in images
         ]

         # create attention mask in numpy
         _lowerCamelCase		:							Union[str, Any]            =					[(image.sum(axis=-1						) != 0).astype(np.floataa						) for image in images]

         _lowerCamelCase		:							str            =					BatchFeature(
             data={'''flattened_patches''': images, '''attention_mask''': attention_masks}		,   tensor_type=__lowerCAmelCase						)

         return encoded_outputs








import gc
import random
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

import diffusers
from diffusers import (
    AutoencoderKL,
    EulerDiscreteScheduler,
    StableDiffusionLatentUpscalePipeline,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.schedulers import KarrasDiffusionSchedulers
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()





def 						__A						(      __lowerCamelCase       ) ->			Optional[int]:
	a									=				[tensor.shape for tensor in tensor_list]
	return all(shape == shapes[0] for shape in shapes[1:]       )

class 						__lowerCAmelCase      (      __magic_name__ ,			__magic_name__ ,			__magic_name__ ,			unittest.TestCase					):
							UpperCamelCase__   	=    StableDiffusionLatentUpscalePipeline
							UpperCamelCase__   	=    TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
							    '''height''',
							    '''width''',
							    '''cross_attention_kwargs''',
							    '''negative_prompt_embeds''',
							    '''prompt_embeds''',
							}
							UpperCamelCase__   	=    PipelineTesterMixin.required_optional_params - {'''num_images_per_prompt'''}
							UpperCamelCase__   	=    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
							UpperCamelCase__   	=    frozenset(
							    []					)  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
							UpperCamelCase__   	=    frozenset([]					)

							UpperCamelCase__   	=    True
							@property
							def  lowerCamelCase__				(		self		:List[str]							):







								'''simple docstring'''







								a									=				1
								a									=				4
								a									=				(16, 16)

								a									=				floats_tensor((batch_size, num_channels) + sizes						, rng=random.Random(0							)							).to(__magic_name__							)
								return image
							def  lowerCamelCase__				(		self		:Any							):







								'''simple docstring'''







								torch.manual_seed(0							)
								a									=				UNetaDConditionModel(
								    act_fn="""gelu"""						, attention_head_dim=8						, norm_num_groups=__magic_name__						, block_out_channels=[32, 32, 64, 64]						, time_cond_proj_dim=160						, conv_in_kernel=1						, conv_out_kernel=1						, cross_attention_dim=32						, down_block_types=(
								        """KDownBlock2D""",
								        """KCrossAttnDownBlock2D""",
								        """KCrossAttnDownBlock2D""",
								        """KCrossAttnDownBlock2D""",
								    )						, in_channels=8						, mid_block_type=__magic_name__						, only_cross_attention=__magic_name__						, out_channels=5						, resnet_time_scale_shift="""scale_shift"""						, time_embedding_type="""fourier"""						, timestep_post_act="""gelu"""						, up_block_types=("""KCrossAttnUpBlock2D""", """KCrossAttnUpBlock2D""", """KCrossAttnUpBlock2D""", """KUpBlock2D""")						, )
								a									=				AutoencoderKL(
								    block_out_channels=[32, 32, 64, 64]						, in_channels=3						, out_channels=3						, down_block_types=[
								        """DownEncoderBlock2D""",
								        """DownEncoderBlock2D""",
								        """DownEncoderBlock2D""",
								        """DownEncoderBlock2D""",
								    ]						, up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D""", """UpDecoderBlock2D""", """UpDecoderBlock2D"""]						, latent_channels=4						, )
								a									=				EulerDiscreteScheduler(prediction_type="""sample"""							)
								a									=				CLIPTextConfig(
								    bos_token_id=0						, eos_token_id=2						, hidden_size=32						, intermediate_size=37						, layer_norm_eps=1E-0_5						, num_attention_heads=4						, num_hidden_layers=5						, pad_token_id=1						, vocab_size=1000						, hidden_act="""quick_gelu"""						, projection_dim=512						, )
								a									=				CLIPTextModel(__magic_name__							)
								a									=				CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""							)

								a									=				{
								    """unet""": model.eval(),
								    """vae""": vae.eval(),
								    """scheduler""": scheduler,
								    """text_encoder""": text_encoder,
								    """tokenizer""": tokenizer,
								}

								return components
							def  lowerCamelCase__				(		self		:Optional[int]						, __magic_name__		:Tuple						, __magic_name__		:Optional[int]=0							):







								'''simple docstring'''







								if str(__magic_name__							).startswith("""mps"""							):
									a									=				torch.manual_seed(__magic_name__							)
								else:
									a									=				torch.Generator(device=__magic_name__							).manual_seed(__magic_name__							)
								a									=				{
								    """prompt""": """A painting of a squirrel eating a burger""",
								    """image""": self.dummy_image.cpu(),
								    """generator""": generator,
								    """num_inference_steps""": 2,
								    """output_type""": """numpy""",
								}
								return inputs
							def  lowerCamelCase__				(		self		:Optional[int]							):







								'''simple docstring'''







								a									=				"""cpu"""

								a									=				self.get_dummy_components()
								a									=				self.pipeline_class(**__magic_name__							)
								pipe.to(__magic_name__							)
								pipe.set_progress_bar_config(disable=__magic_name__							)

								a									=				self.get_dummy_inputs(__magic_name__							)
								a									=				pipe(**__magic_name__							).images
								a									=				image[0, -3:, -3:, -1]

								self.assertEqual(image.shape						, (1, 256, 256, 3)							)
								a									=				np.array(
								    [0.47222412, 0.41921633, 0.44717434, 0.46874192, 0.42588258, 0.46150726, 0.4677534, 0.45583832, 0.48579055]							)
								a									=				np.abs(image_slice.flatten() - expected_slice							).max()
								self.assertLessEqual(__magic_name__						, 1E-3							)
							def  lowerCamelCase__				(		self		:Any							):







								'''simple docstring'''







								super().test_attention_slicing_forward_pass(expected_max_diff=7E-3							)
							def  lowerCamelCase__				(		self		:Optional[int]							):







								'''simple docstring'''







								super().test_cpu_offload_forward_pass(expected_max_diff=3E-3							)
							def  lowerCamelCase__				(		self		:Dict							):







								'''simple docstring'''







								super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3							)
							def  lowerCamelCase__				(		self		:List[Any]							):







								'''simple docstring'''







								super().test_inference_batch_single_identical(expected_max_diff=7E-3							)
							def  lowerCamelCase__				(		self		:Optional[int]							):







								'''simple docstring'''







								super().test_pt_np_pil_outputs_equivalent(expected_max_diff=3E-3							)
							def  lowerCamelCase__				(		self		:str							):







								'''simple docstring'''







								super().test_save_load_local(expected_max_difference=3E-3							)
							def  lowerCamelCase__				(		self		:Tuple							):







								'''simple docstring'''







								super().test_save_load_optional_components(expected_max_difference=3E-3							)





							def  lowerCamelCase__				(		self		:List[str]							):







								'''simple docstring'''







								a									=				[
								    """DDIMScheduler""",
								    """DDPMScheduler""",
								    """PNDMScheduler""",
								    """HeunDiscreteScheduler""",
								    """EulerAncestralDiscreteScheduler""",
								    """KDPM2DiscreteScheduler""",
								    """KDPM2AncestralDiscreteScheduler""",
								    """DPMSolverSDEScheduler""",
								]
								a									=				self.get_dummy_components()
								a									=				self.pipeline_class(**__magic_name__							)

								# make sure that PNDM does not need warm-up
								pipe.scheduler.register_to_config(skip_prk_steps=__magic_name__							)

								pipe.to(__magic_name__							)
								pipe.set_progress_bar_config(disable=__magic_name__							)
								a									=				self.get_dummy_inputs(__magic_name__							)
								a									=				2

								a									=				[]
								for scheduler_enum in KarrasDiffusionSchedulers:
									if scheduler_enum.name in skip_schedulers:
										# no sigma schedulers are not supported
										# no schedulers
										continue

									a									=				getattr(__magic_name__						, scheduler_enum.name							)
									a									=				scheduler_cls.from_config(pipe.scheduler.config							)
									a									=				pipe(**__magic_name__							)[0]
									outputs.append(__magic_name__							)

								assert check_same_shape(__magic_name__							)







@require_torch_gpu
@slow
class 						__lowerCAmelCase      (      unittest.TestCase					):
							def  lowerCamelCase__				(		self		:List[str]							):







								'''simple docstring'''







								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()
							def  lowerCamelCase__				(		self		:List[Any]							):







								'''simple docstring'''







								a									=				torch.manual_seed(33							)

								a									=				StableDiffusionPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4"""						, torch_dtype=torch.floataa							)
								pipe.to("""cuda"""							)

								a									=				StableDiffusionLatentUpscalePipeline.from_pretrained(
								    """stabilityai/sd-x2-latent-upscaler"""						, torch_dtype=torch.floataa							)
								upscaler.to("""cuda"""							)

								a									=				"""a photo of an astronaut high resolution, unreal engine, ultra realistic"""

								a									=				pipe(__magic_name__						, generator=__magic_name__						, output_type="""latent"""							).images

								a									=				upscaler(
								    prompt=__magic_name__						, image=__magic_name__						, num_inference_steps=20						, guidance_scale=0						, generator=__magic_name__						, output_type="""np"""						, ).images[0]

								a									=				load_numpy(
								    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/astronaut_1024.npy"""							)
								assert np.abs((expected_image - image).mean()							) < 5E-2





							def  lowerCamelCase__				(		self		:Optional[Any]							):







								'''simple docstring'''







								a									=				torch.manual_seed(33							)

								a									=				StableDiffusionLatentUpscalePipeline.from_pretrained(
								    """stabilityai/sd-x2-latent-upscaler"""						, torch_dtype=torch.floataa							)
								upscaler.to("""cuda"""							)

								a									=				"""the temple of fire by Ross Tran and Gerardo Dottori, oil on canvas"""

								a									=				load_image(
								    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_512.png"""							)

								a									=				upscaler(
								    prompt=__magic_name__						, image=__magic_name__						, num_inference_steps=20						, guidance_scale=0						, generator=__magic_name__						, output_type="""np"""						, ).images[0]

								a									=				load_numpy(
								    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_1024.npy"""							)
								assert np.abs((expected_image - image).max()							) < 5E-2

