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    :   List[Any]     =      PaintByExamplePipeline
 __lowerCamelCase    :   Optional[Any]     =      IMAGE_GUIDED_IMAGE_INPAINTING_PARAMS
 __lowerCamelCase    :   Dict     =      IMAGE_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
 __lowerCamelCase    :   Union[str, Any]     =      frozenset([]   )  # TO_DO: update the image_prams once refactored VaeImageProcessor.preprocess
 def 	UpperCAmelCase__       (  self						)	->							List[Any]:
       '''simple docstring'''





       torch.manual_seed(0						)
       UpperCAmelCase    : Optional[int]      =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    : Union[str, Any]      =PNDMScheduler(skip_prk_steps=snake_case__						)
       torch.manual_seed(0						)
       UpperCAmelCase    : List[Any]      =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    : List[str]      =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    : List[Any]      =PaintByExampleImageEncoder(snake_case__		,   proj_size=32						)
       UpperCAmelCase    : Union[str, Any]      =CLIPImageProcessor(crop_size=32		,   size=32						)

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





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





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

       if str(snake_case__						).startswith('''mps'''						):
             UpperCAmelCase    : Any      =torch.manual_seed(snake_case__						)
       else:
             UpperCAmelCase    : Any      =torch.Generator(device=snake_case__						).manual_seed(snake_case__						)
       UpperCAmelCase    : Any      ={
           '''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						)	->							str:
       '''simple docstring'''





       UpperCAmelCase    : List[Any]      =self.get_dummy_components()

       # make sure here that pndm scheduler skips prk
       UpperCAmelCase    : List[str]      =PaintByExamplePipeline(**snake_case__						)
       UpperCAmelCase    : Tuple      =pipe.to('''cpu'''						)
       pipe.set_progress_bar_config(disable=snake_case__						)

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

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

       assert image.shape == (1, 64, 64, 3)
       UpperCAmelCase    : 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						)	->							Dict:
       '''simple docstring'''





       UpperCAmelCase    : int      ='''cpu'''
       UpperCAmelCase    : int      =self.get_dummy_inputs()
       inputs.pop('''mask_image'''						)
       UpperCAmelCase    : Any      =self.convert_to_pt(inputs.pop('''image'''						)						)
       UpperCAmelCase    : Tuple      =image.clamp(0		,   1						) / 2

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

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

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

       UpperCAmelCase    : Any      =Image.fromarray(np.uinta(snake_case__						)						).convert('''RGB'''						)
       UpperCAmelCase    : str      =Image.fromarray(np.uinta(snake_case__						)						).convert('''RGB'''						)

       UpperCAmelCase    : Union[str, Any]      =pipe(**self.get_dummy_inputs()						)
       UpperCAmelCase    : Union[str, 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						)	->							Union[str, Any]:
       '''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						)	->							Optional[Any]:
       '''simple docstring'''





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






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





       UpperCAmelCase    : Dict      =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    : Tuple      =load_image(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/paint_by_example/panda.jpg'''						)

       UpperCAmelCase    : Any      =PaintByExamplePipeline.from_pretrained('''Fantasy-Studio/Paint-by-Example'''						)
       UpperCAmelCase    : List[str]      =pipe.to(snake_case__						)
       pipe.set_progress_bar_config(disable=snake_case__						)

       UpperCAmelCase    : Optional[Any]      =torch.manual_seed(321						)
       UpperCAmelCase    : List[Any]      =pipe(
           image=snake_case__		,   mask_image=snake_case__		,   example_image=snake_case__		,   generator=snake_case__		,   guidance_scale=5.0		,   num_inference_steps=50		,   output_type='''np'''		,   )

       UpperCAmelCase    : List[Any]      =output.images

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

       assert image.shape == (1, 512, 512, 3)
       UpperCAmelCase    : Optional[Any]      =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() = }')
