




import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPImageProcessor, CLIPVisionConfig

from diffusers import AutoencoderKL, PaintByExamplePipeline, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.paint_by_example import PaintByExampleImageEncoder
from diffusers.utils import floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import IMAGE_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, IMAGE_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()







class 			__snake_case   (     lowerCAmelCase_					,   unittest.TestCase   ):
 __lowerCamelCase    :   str     =      PaintByExamplePipeline
 __lowerCamelCase    :   List[Any]     =      IMAGE_GUIDED_IMAGE_INPAINTING_PARAMS
 __lowerCamelCase    :   List[str]     =      IMAGE_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
 __lowerCamelCase    :   int     =      frozenset([]   )  # TO_DO: update the image_prams once refactored VaeImageProcessor.preprocess
 def 	UpperCAmelCase__       (  self						)	->							Tuple:
       '''simple docstring'''





       torch.manual_seed(0						)
       UpperCAmelCase    : Optional[Any]      =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		,   )
       UpperCAmelCase    : Optional[int]      =PNDMScheduler(skip_prk_steps=__SCREAMING_SNAKE_CASE						)
       torch.manual_seed(0						)
       UpperCAmelCase    : Optional[int]      =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		,   )
       torch.manual_seed(0						)
       UpperCAmelCase    : Optional[Any]      =CLIPVisionConfig(
           hidden_size=32		,   projection_dim=32		,   intermediate_size=37		,   layer_norm_eps=1e-05		,   num_attention_heads=4		,   num_hidden_layers=5		,   image_size=32		,   patch_size=4		,   )
       UpperCAmelCase    : Union[str, Any]      =PaintByExampleImageEncoder(__SCREAMING_SNAKE_CASE		,   proj_size=32						)
       UpperCAmelCase    : int      =CLIPImageProcessor(crop_size=32		,   size=32						)

       UpperCAmelCase    : Tuple      ={
           '''unet''': unet,
           '''scheduler''': scheduler,
           '''vae''': vae,
           '''image_encoder''': image_encoder,
           '''safety_checker''': None,
           '''feature_extractor''': feature_extractor,
       }
       return components
 def 	UpperCAmelCase__       (  self		,   snake_case__						)	->							str:
       '''simple docstring'''





       UpperCAmelCase    : Tuple      =np.array(image.convert('''RGB'''						)						)
       UpperCAmelCase    : List[str]      =image[None].transpose(0		,   3		,   1		,   2						)
       UpperCAmelCase    : List[Any]      =torch.from_numpy(__SCREAMING_SNAKE_CASE						).to(dtype=torch.floataa						) / 127.5 - 1.0
       return image
 def 	UpperCAmelCase__       (  self		,   snake_case__="cpu"		,   snake_case__=0						)	->							Union[str, Any]:
       '''simple docstring'''





       UpperCAmelCase    : Optional[Any]      =floats_tensor((1, 3, 32, 32)		,   rng=random.Random(__SCREAMING_SNAKE_CASE						)						).to(__SCREAMING_SNAKE_CASE						)
       UpperCAmelCase    : Dict      =image.cpu().permute(0		,   2		,   3		,   1						)[0]
       UpperCAmelCase    : Tuple      =Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE						)						).convert('''RGB'''						).resize((64, 64)						)
       UpperCAmelCase    : int      =Image.fromarray(np.uinta(image + 4						)						).convert('''RGB'''						).resize((64, 64)						)
       UpperCAmelCase    : List[Any]      =Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE						)						).convert('''RGB'''						).resize((32, 32)						)

       if str(__SCREAMING_SNAKE_CASE						).startswith('''mps'''						):
             UpperCAmelCase    : int      =torch.manual_seed(__SCREAMING_SNAKE_CASE						)
       else:
             UpperCAmelCase    : Optional[int]      =torch.Generator(device=__SCREAMING_SNAKE_CASE						).manual_seed(__SCREAMING_SNAKE_CASE						)
       UpperCAmelCase    : int      ={
           '''example_image''': example_image,
           '''image''': init_image,
           '''mask_image''': mask_image,
           '''generator''': generator,
           '''num_inference_steps''': 2,
           '''guidance_scale''': 6.0,
           '''output_type''': '''numpy''',
       }
       return inputs
 def 	UpperCAmelCase__       (  self						)	->							Tuple:
       '''simple docstring'''





       UpperCAmelCase    : int      =self.get_dummy_components()

       # make sure here that pndm scheduler skips prk
       UpperCAmelCase    : Union[str, Any]      =PaintByExamplePipeline(**__SCREAMING_SNAKE_CASE						)
       UpperCAmelCase    : Dict      =pipe.to('''cpu'''						)
       pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE						)

       UpperCAmelCase    : str      =self.get_dummy_inputs()
       UpperCAmelCase    : Dict      =pipe(**__SCREAMING_SNAKE_CASE						)
       UpperCAmelCase    : Union[str, Any]      =output.images

       UpperCAmelCase    : Dict      =image[0, -3:, -3:, -1]

       assert image.shape == (1, 64, 64, 3)
       UpperCAmelCase    : Optional[int]      =np.array([0.4686, 0.5687, 0.4007, 0.5218, 0.5741, 0.4482, 0.4940, 0.4629, 0.4503]						)

       assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-2
 def 	UpperCAmelCase__       (  self						)	->							int:
       '''simple docstring'''





       UpperCAmelCase    : Union[str, Any]      ='''cpu'''
       UpperCAmelCase    : Dict      =self.get_dummy_inputs()
       inputs.pop('''mask_image'''						)
       UpperCAmelCase    : str      =self.convert_to_pt(inputs.pop('''image'''						)						)
       UpperCAmelCase    : Any      =image.clamp(0		,   1						) / 2

       # make sure here that pndm scheduler skips prk
       UpperCAmelCase    : Optional[Any]      =PaintByExamplePipeline(**self.get_dummy_components()						)
       UpperCAmelCase    : Dict      =pipe.to(__SCREAMING_SNAKE_CASE						)
       pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE						)

       UpperCAmelCase    : int      =pipe(image=__SCREAMING_SNAKE_CASE		,   mask_image=mask_image[:, 0]		,   **__SCREAMING_SNAKE_CASE						)
       UpperCAmelCase    : Optional[int]      =output.images

       UpperCAmelCase    : Dict      =image.cpu().permute(0		,   2		,   3		,   1						)[0]
       UpperCAmelCase    : Tuple      =mask_image.cpu().permute(0		,   2		,   3		,   1						)[0]

       UpperCAmelCase    : Tuple      =Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE						)						).convert('''RGB'''						)
       UpperCAmelCase    : Any      =Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE						)						).convert('''RGB'''						)

       UpperCAmelCase    : Any      =pipe(**self.get_dummy_inputs()						)
       UpperCAmelCase    : List[Any]      =output.images

       assert out_a.shape == (1, 64, 64, 3)
       assert np.abs(out_a.flatten() - out_a.flatten()						).max() < 5e-2






 def 	UpperCAmelCase__       (  self						)	->							Dict:
       '''simple docstring'''





       super().test_inference_batch_single_identical(expected_max_diff=3e-3						)







@slow
@require_torch_gpu
class 			__snake_case   (     unittest.TestCase   ):
 def 	UpperCAmelCase__       (  self						)	->							Any:
       '''simple docstring'''





       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()






 def 	UpperCAmelCase__       (  self						)	->							Union[str, Any]:
       '''simple docstring'''





       UpperCAmelCase    : str      =load_image(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/paint_by_example/dog_in_bucket.png'''						)
       UpperCAmelCase    : Dict      =load_image(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/paint_by_example/mask.png'''						)
       UpperCAmelCase    : List[str]      =load_image(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/paint_by_example/panda.jpg'''						)

       UpperCAmelCase    : Dict      =PaintByExamplePipeline.from_pretrained('''Fantasy-Studio/Paint-by-Example'''						)
       UpperCAmelCase    : str      =pipe.to(__SCREAMING_SNAKE_CASE						)
       pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE						)

       UpperCAmelCase    : Tuple      =torch.manual_seed(321						)
       UpperCAmelCase    : Any      =pipe(
           image=__SCREAMING_SNAKE_CASE		,   mask_image=__SCREAMING_SNAKE_CASE		,   example_image=__SCREAMING_SNAKE_CASE		,   generator=__SCREAMING_SNAKE_CASE		,   guidance_scale=5.0		,   num_inference_steps=50		,   output_type='''np'''		,   )

       UpperCAmelCase    : Tuple      =output.images

       UpperCAmelCase    : int      =image[0, -3:, -3:, -1]

       assert image.shape == (1, 512, 512, 3)
       UpperCAmelCase    : Optional[int]      =np.array([0.4834, 0.4811, 0.4874, 0.5122, 0.5081, 0.5144, 0.5291, 0.5290, 0.5374]						)

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

from collections import defaultdict





def   lowerCAmelCase_ (				__lowerCAmelCase = 5						)->  int:






      '''simple docstring'''





      UpperCAmelCase    : List[str]      =defaultdict(__lowerCAmelCase						)
      UpperCAmelCase    : Tuple      =0

      while True:
            UpperCAmelCase    : Any      =get_digits(__lowerCAmelCase						)
            freqs[digits].append(__lowerCAmelCase						)

            if len(freqs[digits]						) == max_base:
                  UpperCAmelCase    : Optional[int]      =freqs[digits][0] ** 3
                  return base

            num += 1





def   lowerCAmelCase_ (				__lowerCAmelCase						)->  str:






      '''simple docstring'''





      return "".join(sorted(str(num**3						)						)						)


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