






import gc
import random
import unittest

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

from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow

from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()
class 		SCREAMING_SNAKE_CASE__	(  UpperCAmelCase					,      UpperCAmelCase					,      UpperCAmelCase					,      unittest.TestCase     ):

  '''simple docstring'''







  _lowerCamelCase    =  StableDiffusionInpaintPipeline
  _lowerCamelCase    =  TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
  _lowerCamelCase    =  TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
  _lowerCamelCase    =  frozenset(
      []     )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
  _lowerCamelCase    =  frozenset([]     )


  def  lowerCamelCase       (      self		:			Tuple							)						->	Optional[int]:


         """simple docstring"""
         torch.manual_seed(0							)
         _UpperCAmelCase							=    UNetaDConditionModel(
             block_out_channels=(32, 64)       ,				layers_per_block=2       ,				sample_size=32       ,				in_channels=9       ,				out_channels=4       ,				down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")       ,				up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")       ,				cross_attention_dim=32       ,				attention_head_dim=(2, 4)       ,				use_linear_projection=lowerCamelCase       ,				)
         _UpperCAmelCase							=    PNDMScheduler(skip_prk_steps=lowerCamelCase							)
         torch.manual_seed(0							)
         _UpperCAmelCase							=    AutoencoderKL(
             block_out_channels=[32, 64]       ,				in_channels=3       ,				out_channels=3       ,				down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]       ,				up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]       ,				latent_channels=4       ,				sample_size=128       ,				)
         torch.manual_seed(0							)
         _UpperCAmelCase							=    CLIPTextConfig(
             bos_token_id=0       ,				eos_token_id=2       ,				hidden_size=32       ,				intermediate_size=37       ,				layer_norm_eps=1E-05       ,				num_attention_heads=4       ,				num_hidden_layers=5       ,				pad_token_id=1       ,				vocab_size=1000       ,				hidden_act="""gelu"""       ,				projection_dim=512       ,				)
         _UpperCAmelCase							=    CLIPTextModel(lowerCamelCase							)
         _UpperCAmelCase							=    CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""							)

         _UpperCAmelCase							=    {
             """unet""": unet,
             """scheduler""": scheduler,
             """vae""": vae,
             """text_encoder""": text_encoder,
             """tokenizer""": tokenizer,
             """safety_checker""": None,
             """feature_extractor""": None,
         }
         return components


  def  lowerCamelCase       (      self		:			Optional[int]       ,				lowerCamelCase		:			Optional[int]       ,				lowerCamelCase		:			Optional[Any]=0							)						->	Optional[int]:


         """simple docstring"""
         # TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched
         _UpperCAmelCase							=    floats_tensor((1, 3, 32, 32)       ,				rng=random.Random(lowerCamelCase							)							).to(lowerCamelCase							)
         _UpperCAmelCase							=    image.cpu().permute(0       ,				2       ,				3       ,				1							)[0]
         _UpperCAmelCase							=    Image.fromarray(np.uinta(lowerCamelCase							)							).convert("""RGB"""							).resize((64, 64)							)
         _UpperCAmelCase							=    Image.fromarray(np.uinta(image + 4							)							).convert("""RGB"""							).resize((64, 64)							)
         if str(lowerCamelCase							).startswith("""mps"""							):
                _UpperCAmelCase							=    torch.manual_seed(lowerCamelCase							)
         else:
                _UpperCAmelCase							=    torch.Generator(device=lowerCamelCase							).manual_seed(lowerCamelCase							)
         _UpperCAmelCase							=    {
             """prompt""": """A painting of a squirrel eating a burger""",
             """image""": init_image,
             """mask_image""": mask_image,
             """generator""": generator,
             """num_inference_steps""": 2,
             """guidance_scale""": 6.0,
             """output_type""": """numpy""",
         }
         return inputs


  def  lowerCamelCase       (      self		:			Optional[int]							)						->	Any:


         """simple docstring"""
         _UpperCAmelCase							=    """cpu"""  # ensure determinism for the device-dependent torch.Generator
         _UpperCAmelCase							=    self.get_dummy_components()
         _UpperCAmelCase							=    StableDiffusionInpaintPipeline(**lowerCamelCase							)
         _UpperCAmelCase							=    sd_pipe.to(lowerCamelCase							)
         sd_pipe.set_progress_bar_config(disable=lowerCamelCase							)

         _UpperCAmelCase							=    self.get_dummy_inputs(lowerCamelCase							)
         _UpperCAmelCase							=    sd_pipe(**lowerCamelCase							).images
         _UpperCAmelCase							=    image[0, -3:, -3:, -1]

         assert image.shape == (1, 64, 64, 3)
         _UpperCAmelCase							=    np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476]							)

         assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-2





  def  lowerCamelCase       (      self		:			Tuple							)						->	Tuple:


         """simple docstring"""
         super().test_inference_batch_single_identical(expected_max_diff=3E-3							)



@slow
@require_torch_gpu
class 		SCREAMING_SNAKE_CASE__	(  unittest.TestCase     ):

  '''simple docstring'''







  def  lowerCamelCase       (      self		:			Dict							)						->	int:


         """simple docstring"""
         # clean up the VRAM after each test
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()


  def  lowerCamelCase       (      self		:			Any							)						->	List[Any]:


         """simple docstring"""
         _UpperCAmelCase							=    load_image(
             """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
             """/sd2-inpaint/init_image.png"""							)
         _UpperCAmelCase							=    load_image(
             """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png"""							)
         _UpperCAmelCase							=    load_numpy(
             """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint"""
             """/yellow_cat_sitting_on_a_park_bench.npy"""							)

         _UpperCAmelCase							=    """stabilityai/stable-diffusion-2-inpainting"""
         _UpperCAmelCase							=    StableDiffusionInpaintPipeline.from_pretrained(lowerCamelCase       ,				safety_checker=lowerCamelCase							)
         pipe.to(lowerCamelCase							)
         pipe.set_progress_bar_config(disable=lowerCamelCase							)
         pipe.enable_attention_slicing()

         _UpperCAmelCase							=    """Face of a yellow cat, high resolution, sitting on a park bench"""

         _UpperCAmelCase							=    torch.manual_seed(0							)
         _UpperCAmelCase							=    pipe(
             prompt=lowerCamelCase       ,				image=lowerCamelCase       ,				mask_image=lowerCamelCase       ,				generator=lowerCamelCase       ,				output_type="""np"""       ,				)
         _UpperCAmelCase							=    output.images[0]

         assert image.shape == (512, 512, 3)
         assert np.abs(expected_image - image							).max() < 9E-3


  def  lowerCamelCase       (      self		:			int							)						->	str:


         """simple docstring"""
         _UpperCAmelCase							=    load_image(
             """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
             """/sd2-inpaint/init_image.png"""							)
         _UpperCAmelCase							=    load_image(
             """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png"""							)
         _UpperCAmelCase							=    load_numpy(
             """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint"""
             """/yellow_cat_sitting_on_a_park_bench_fp16.npy"""							)

         _UpperCAmelCase							=    """stabilityai/stable-diffusion-2-inpainting"""
         _UpperCAmelCase							=    StableDiffusionInpaintPipeline.from_pretrained(
             lowerCamelCase       ,				torch_dtype=torch.floataa       ,				safety_checker=lowerCamelCase       ,				)
         pipe.to(lowerCamelCase							)
         pipe.set_progress_bar_config(disable=lowerCamelCase							)
         pipe.enable_attention_slicing()

         _UpperCAmelCase							=    """Face of a yellow cat, high resolution, sitting on a park bench"""

         _UpperCAmelCase							=    torch.manual_seed(0							)
         _UpperCAmelCase							=    pipe(
             prompt=lowerCamelCase       ,				image=lowerCamelCase       ,				mask_image=lowerCamelCase       ,				generator=lowerCamelCase       ,				output_type="""np"""       ,				)
         _UpperCAmelCase							=    output.images[0]

         assert image.shape == (512, 512, 3)
         assert np.abs(expected_image - image							).max() < 5E-1





  def  lowerCamelCase       (      self		:			Union[str, Any]							)						->	List[Any]:


         """simple docstring"""
         torch.cuda.empty_cache()
         torch.cuda.reset_max_memory_allocated()
         torch.cuda.reset_peak_memory_stats()

         _UpperCAmelCase							=    load_image(
             """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
             """/sd2-inpaint/init_image.png"""							)
         _UpperCAmelCase							=    load_image(
             """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png"""							)

         _UpperCAmelCase							=    """stabilityai/stable-diffusion-2-inpainting"""
         _UpperCAmelCase							=    PNDMScheduler.from_pretrained(lowerCamelCase       ,				subfolder="""scheduler"""							)
         _UpperCAmelCase							=    StableDiffusionInpaintPipeline.from_pretrained(
             lowerCamelCase       ,				safety_checker=lowerCamelCase       ,				scheduler=lowerCamelCase       ,				torch_dtype=torch.floataa       ,				)
         pipe.to(lowerCamelCase							)
         pipe.set_progress_bar_config(disable=lowerCamelCase							)
         pipe.enable_attention_slicing(1							)
         pipe.enable_sequential_cpu_offload()

         _UpperCAmelCase							=    """Face of a yellow cat, high resolution, sitting on a park bench"""

         _UpperCAmelCase							=    torch.manual_seed(0							)
         _UpperCAmelCase							=    pipe(
             prompt=lowerCamelCase       ,				image=lowerCamelCase       ,				mask_image=lowerCamelCase       ,				generator=lowerCamelCase       ,				num_inference_steps=2       ,				output_type="""np"""       ,				)

         _UpperCAmelCase							=    torch.cuda.max_memory_allocated()
         # make sure that less than 2.65 GB is allocated
         assert mem_bytes < 2.65 * 10**9



'''simple docstring'''





from functools import reduce

__lowerCamelCase												=						(
    '''73167176531330624919225119674426574742355349194934'''
    '''96983520312774506326239578318016984801869478851843'''
    '''85861560789112949495459501737958331952853208805511'''
    '''12540698747158523863050715693290963295227443043557'''
    '''66896648950445244523161731856403098711121722383113'''
    '''62229893423380308135336276614282806444486645238749'''
    '''30358907296290491560440772390713810515859307960866'''
    '''70172427121883998797908792274921901699720888093776'''
    '''65727333001053367881220235421809751254540594752243'''
    '''52584907711670556013604839586446706324415722155397'''
    '''53697817977846174064955149290862569321978468622482'''
    '''83972241375657056057490261407972968652414535100474'''
    '''82166370484403199890008895243450658541227588666881'''
    '''16427171479924442928230863465674813919123162824586'''
    '''17866458359124566529476545682848912883142607690042'''
    '''24219022671055626321111109370544217506941658960408'''
    '''07198403850962455444362981230987879927244284909188'''
    '''84580156166097919133875499200524063689912560717606'''
    '''05886116467109405077541002256983155200055935729725'''
    '''71636269561882670428252483600823257530420752963450'''
)


def        a__     (					UpperCamelCase_						:      str = N						):
   return max(
       # mypy cannot properly interpret reduce
       int(reduce(lambda UpperCamelCase_,   UpperCamelCase_						: str(int(UpperCamelCase_						) * int(UpperCamelCase_						)						),   n[i : i + 13]						)						)
       for i in range(len(UpperCamelCase_						) - 12						)						)


if __name__ == "__main__":
    print(F'''{solution() = }''')



