



import gc
import random
import tempfile
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMInverseScheduler,
    DDIMScheduler,
    DPMSolverMultistepInverseScheduler,
    DPMSolverMultistepScheduler,
    StableDiffusionDiffEditPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_image, slow
from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device

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


enable_full_determinism()



class      _UpperCAmelCase      (							A__      ,   A__      ,   unittest.TestCase  ):
     UpperCamelCase__		     =					StableDiffusionDiffEditPipeline
     UpperCamelCase__		     =					TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''}
     UpperCamelCase__		     =					TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''}
     UpperCamelCase__		     =					frozenset(
         []  )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
     UpperCamelCase__		     =					frozenset([]  )




     def 		snake_case_		(					self):
         torch.manual_seed(0)
         A__					=       UNetaDConditionModel(
             block_out_channels=(3_2, 6_4)			,    layers_per_block=2			,    sample_size=3_2			,    in_channels=4			,    out_channels=4			,    down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')			,    up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')			,    cross_attention_dim=3_2			,    attention_head_dim=(2, 4)			,    use_linear_projection=a__			,    )
         A__					=       DDIMScheduler(
             beta_start=0.0_0_0_8_5			,    beta_end=0.0_1_2			,    beta_schedule='''scaled_linear'''			,    clip_sample=a__			,    set_alpha_to_one=a__			,    )
         A__					=       DDIMInverseScheduler(
             beta_start=0.0_0_0_8_5			,    beta_end=0.0_1_2			,    beta_schedule='''scaled_linear'''			,    clip_sample=a__			,    set_alpha_to_zero=a__			,    )
         torch.manual_seed(0)
         A__					=       AutoencoderKL(
             block_out_channels=[3_2, 6_4]			,    in_channels=3			,    out_channels=3			,    down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']			,    up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']			,    latent_channels=4			,    sample_size=1_2_8			,    )
         torch.manual_seed(0)
         A__					=       CLIPTextConfig(
             bos_token_id=0			,    eos_token_id=2			,    hidden_size=3_2			,    intermediate_size=3_7			,    layer_norm_eps=1e-05			,    num_attention_heads=4			,    num_hidden_layers=5			,    pad_token_id=1			,    vocab_size=1_0_0_0			,    hidden_act='''gelu'''			,    projection_dim=5_1_2			,    )
         A__					=       CLIPTextModel(a__)
         A__					=       CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''')

         A__					=       {
             '''unet''': unet,
             '''scheduler''': scheduler,
             '''inverse_scheduler''': inverse_scheduler,
             '''vae''': vae,
             '''text_encoder''': text_encoder,
             '''tokenizer''': tokenizer,
             '''safety_checker''': None,
             '''feature_extractor''': None,
         }

         return components




     def 		snake_case_		(					self			,    a__			,    a__=0):
         A__					=       floats_tensor((1, 1_6, 1_6)			,    rng=random.Random(a__)).to(a__)
         A__					=       floats_tensor((1, 2, 4, 1_6, 1_6)			,    rng=random.Random(a__)).to(a__)
         if str(a__).startswith('''mps'''):
             A__					=       torch.manual_seed(a__)
         else:
             A__					=       torch.Generator(device=a__).manual_seed(a__)
         A__					=       {
             '''prompt''': '''a dog and a newt''',
             '''mask_image''': mask,
             '''image_latents''': latents,
             '''generator''': generator,
             '''num_inference_steps''': 2,
             '''inpaint_strength''': 1.0,
             '''guidance_scale''': 6.0,
             '''output_type''': '''numpy''',
         }

         return inputs




     def 		snake_case_		(					self			,    a__			,    a__=0):
         A__					=       floats_tensor((1, 3, 3_2, 3_2)			,    rng=random.Random(a__)).to(a__)
         A__					=       image.cpu().permute(0			,    2			,    3			,    1)[0]
         A__					=       Image.fromarray(np.uinta(a__)).convert('''RGB''')
         if str(a__).startswith('''mps'''):
             A__					=       torch.manual_seed(a__)
         else:
             A__					=       torch.Generator(device=a__).manual_seed(a__)
         A__					=       {
             '''image''': image,
             '''source_prompt''': '''a cat and a frog''',
             '''target_prompt''': '''a dog and a newt''',
             '''generator''': generator,
             '''num_inference_steps''': 2,
             '''num_maps_per_mask''': 2,
             '''mask_encode_strength''': 1.0,
             '''guidance_scale''': 6.0,
             '''output_type''': '''numpy''',
         }

         return inputs




     def 		snake_case_		(					self			,    a__			,    a__=0):
         A__					=       floats_tensor((1, 3, 3_2, 3_2)			,    rng=random.Random(a__)).to(a__)
         A__					=       image.cpu().permute(0			,    2			,    3			,    1)[0]
         A__					=       Image.fromarray(np.uinta(a__)).convert('''RGB''')
         if str(a__).startswith('''mps'''):
             A__					=       torch.manual_seed(a__)
         else:
             A__					=       torch.Generator(device=a__).manual_seed(a__)
         A__					=       {
             '''image''': image,
             '''prompt''': '''a cat and a frog''',
             '''generator''': generator,
             '''num_inference_steps''': 2,
             '''inpaint_strength''': 1.0,
             '''guidance_scale''': 6.0,
             '''decode_latents''': True,
             '''output_type''': '''numpy''',
         }
         return inputs




     def 		snake_case_		(					self):
         if not hasattr(self.pipeline_class			,    '''_optional_components'''):
             return

         A__					=       self.get_dummy_components()
         A__					=       self.pipeline_class(**a__)
         pipe.to(a__)
         pipe.set_progress_bar_config(disable=a__)

         # set all optional components to None and update pipeline config accordingly
         for optional_component in pipe._optional_components:
             setattr(a__			,    a__			,    a__)
         pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components})

         A__					=       self.get_dummy_inputs(a__)
         A__					=       pipe(**a__)[0]

         with tempfile.TemporaryDirectory() as tmpdir:
             pipe.save_pretrained(a__)
             A__					=       self.pipeline_class.from_pretrained(a__)
             pipe_loaded.to(a__)
             pipe_loaded.set_progress_bar_config(disable=a__)

         for optional_component in pipe._optional_components:
             self.assertTrue(
                 getattr(a__			,    a__) is None			,    F"`{optional_component}` did not stay set to None after loading."			,    )

         A__					=       self.get_dummy_inputs(a__)
         A__					=       pipe_loaded(**a__)[0]

         A__					=       np.abs(output - output_loaded).max()
         self.assertLess(a__			,    1e-4)




     def 		snake_case_		(					self):
         A__					=       '''cpu'''

         A__					=       self.get_dummy_components()
         A__					=       self.pipeline_class(**a__)
         pipe.to(a__)
         pipe.set_progress_bar_config(disable=a__)

         A__					=       self.get_dummy_mask_inputs(a__)
         A__					=       pipe.generate_mask(**a__)
         A__					=       mask[0, -3:, -3:]

         self.assertEqual(mask.shape			,    (1, 1_6, 1_6))
         A__					=       np.array([0] * 9)
         A__					=       np.abs(mask_slice.flatten() - expected_slice).max()
         self.assertLessEqual(a__			,    1e-3)
         self.assertEqual(mask[0, -3, -4]			,    0)




     def 		snake_case_		(					self):
         A__					=       '''cpu'''

         A__					=       self.get_dummy_components()
         A__					=       self.pipeline_class(**a__)
         pipe.to(a__)
         pipe.set_progress_bar_config(disable=a__)

         A__					=       self.get_dummy_inversion_inputs(a__)
         A__					=       pipe.invert(**a__).images
         A__					=       image[0, -1, -3:, -3:]

         self.assertEqual(image.shape			,    (2, 3_2, 3_2, 3))
         A__					=       np.array(
             [0.5_1_5_0, 0.5_1_3_4, 0.5_0_4_3, 0.5_3_7_6, 0.4_6_9_4, 0.5_1_0_5_0, 0.5_0_1_5, 0.4_4_0_7, 0.4_7_9_9]			,    )
         A__					=       np.abs(image_slice.flatten() - expected_slice).max()
         self.assertLessEqual(a__			,    1e-3)




     def 		snake_case_		(					self):
         super().test_inference_batch_single_identical(expected_max_diff=5e-3)




     def 		snake_case_		(					self):
         A__					=       '''cpu'''

         A__					=       self.get_dummy_components()

         A__					=       {'''beta_start''': 0.0_0_0_8_5, '''beta_end''': 0.0_1_2, '''beta_schedule''': '''scaled_linear'''}
         A__					=       DPMSolverMultistepScheduler(**a__)
         A__					=       DPMSolverMultistepInverseScheduler(**a__)

         A__					=       self.pipeline_class(**a__)
         pipe.to(a__)
         pipe.set_progress_bar_config(disable=a__)

         A__					=       self.get_dummy_inversion_inputs(a__)
         A__					=       pipe.invert(**a__).images
         A__					=       image[0, -1, -3:, -3:]

         self.assertEqual(image.shape			,    (2, 3_2, 3_2, 3))
         A__					=       np.array(
             [0.5_1_5_0, 0.5_1_3_4, 0.5_0_4_3, 0.5_3_7_6, 0.4_6_9_4, 0.5_1_0_5_0, 0.5_0_1_5, 0.4_4_0_7, 0.4_7_9_9]			,    )
         A__					=       np.abs(image_slice.flatten() - expected_slice).max()
         self.assertLessEqual(a__			,    1e-3)







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




     def 		snake_case_		(					self):
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()




     @classmethod
     def 		snake_case_		(					cls):
         A__					=       load_image(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png''')

         A__					=       raw_image.convert('''RGB''').resize((7_6_8, 7_6_8))

         A__					=       raw_image




     def 		snake_case_		(					self):
         A__					=       torch.manual_seed(0)

         A__					=       StableDiffusionDiffEditPipeline.from_pretrained(
             '''stabilityai/stable-diffusion-2-1'''			,    safety_checker=a__			,    torch_dtype=torch.floataa)
         A__					=       DDIMScheduler.from_config(pipe.scheduler.config)
         A__					=       DDIMInverseScheduler.from_config(pipe.scheduler.config)
         pipe.enable_model_cpu_offload()
         pipe.set_progress_bar_config(disable=a__)

         A__					=       '''a bowl of fruit'''
         A__					=       '''a bowl of pears'''

         A__					=       pipe.generate_mask(
             image=self.raw_image			,    source_prompt=a__			,    target_prompt=a__			,    generator=a__			,    )

         A__					=       pipe.invert(
             prompt=a__			,    image=self.raw_image			,    inpaint_strength=0.7			,    generator=a__).latents

         A__					=       pipe(
             prompt=a__			,    mask_image=a__			,    image_latents=a__			,    generator=a__			,    negative_prompt=a__			,    inpaint_strength=0.7			,    output_type='''numpy'''			,    ).images[0]

         A__					=       (
             np.array(
                 load_image(
                     '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
                     '''/diffedit/pears.png''').resize((7_6_8, 7_6_8)))
             / 2_5_5
         )
         assert np.abs((expected_image - image).max()) < 5e-1




     def 		snake_case_		(					self):
         A__					=       torch.manual_seed(0)

         A__					=       StableDiffusionDiffEditPipeline.from_pretrained(
             '''stabilityai/stable-diffusion-2-1'''			,    safety_checker=a__			,    torch_dtype=torch.floataa)
         A__					=       DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
         A__					=       DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config)
         pipe.enable_model_cpu_offload()
         pipe.set_progress_bar_config(disable=a__)

         A__					=       '''a bowl of fruit'''
         A__					=       '''a bowl of pears'''

         A__					=       pipe.generate_mask(
             image=self.raw_image			,    source_prompt=a__			,    target_prompt=a__			,    generator=a__			,    )

         A__					=       pipe.invert(
             prompt=a__			,    image=self.raw_image			,    inpaint_strength=0.7			,    generator=a__			,    num_inference_steps=2_5			,    ).latents

         A__					=       pipe(
             prompt=a__			,    mask_image=a__			,    image_latents=a__			,    generator=a__			,    negative_prompt=a__			,    inpaint_strength=0.7			,    num_inference_steps=2_5			,    output_type='''numpy'''			,    ).images[0]

         A__					=       (
             np.array(
                 load_image(
                     '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
                     '''/diffedit/pears.png''').resize((7_6_8, 7_6_8)))
             / 2_5_5
         )
         assert np.abs((expected_image - image).max()) < 5e-1





from manim import *



class      _UpperCAmelCase      (							A__  ):




     def 		snake_case_		(					self):
         A__					=       Rectangle(height=0.5			,    width=0.5)
         A__					=       Rectangle(height=0.2_5			,    width=0.2_5)
         A__					=       Rectangle(height=0.4_6			,    width=0.4_6).set_stroke(width=0)

         A__					=       [mem.copy() for i in range(6)]
         A__					=       [mem.copy() for i in range(6)]
         A__					=       VGroup(*a__).arrange(a__			,    buff=0)
         A__					=       VGroup(*a__).arrange(a__			,    buff=0)
         A__					=       VGroup(a__			,    a__).arrange(a__			,    buff=0)
         A__					=       Text('''CPU'''			,    font_size=2_4)
         A__					=       Group(a__			,    a__).arrange(a__			,    buff=0.5			,    aligned_edge=a__)
         cpu.move_to([-2.5, -0.5, 0])
         self.add(a__)

         A__					=       [mem.copy() for i in range(4)]
         A__					=       VGroup(*a__).arrange(a__			,    buff=0)
         A__					=       Text('''GPU'''			,    font_size=2_4)
         A__					=       Group(a__			,    a__).arrange(a__			,    buff=0.5			,    aligned_edge=a__)
         gpu.move_to([-1, -1, 0])
         self.add(a__)

         A__					=       [mem.copy() for i in range(6)]
         A__					=       VGroup(*a__).arrange(a__			,    buff=0)

         A__					=       Text('''Model'''			,    font_size=2_4)
         A__					=       Group(a__			,    a__).arrange(a__			,    buff=0.5			,    aligned_edge=a__)
         model.move_to([3, -1.0, 0])
         self.add(a__)

         A__					=       []
         A__					=       []
         A__					=       []

         for i, rect in enumerate(a__):
             rect.set_stroke(a__)

             A__					=       Rectangle(height=0.4_6 / 4			,    width=0.4_6 / 3).set_stroke(width=0.0).set_fill(a__			,    opacity=0.7)

             if i == 0:
                 cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT)			,    buff=0.0_2			,    direction=a__)
                 cpu_target.set_x(cpu_target.get_x() + 0.1)
             elif i == 3:
                 cpu_target.next_to(model_cpu_arr[0]			,    direction=a__			,    buff=0.0)
             else:
                 cpu_target.next_to(model_cpu_arr[i - 1]			,    direction=a__			,    buff=0.0)
             self.add(a__)
             model_cpu_arr.append(a__)

         self.add(*a__			,    *a__			,    *a__)

         A__					=       [mem.copy() for i in range(6)]
         A__					=       VGroup(*a__).arrange(a__			,    buff=0)

         A__					=       Text('''Loaded Checkpoint'''			,    font_size=2_4)
         A__					=       Group(a__			,    a__).arrange(a__			,    buff=0.5			,    aligned_edge=a__)
         checkpoint.move_to([3, 0.5, 0])

         self.add(a__)

         A__					=       []
         A__					=       []

         for i, rect in enumerate(a__):
             A__					=       fill.copy().set_fill(a__			,    opacity=0.7)
             target.move_to(a__)
             ckpt_arr.append(a__)

             A__					=       target.copy()
             if i < 5:
                 cpu_target.move_to(cpu_left_col_base[i + 1])
             else:
                 cpu_target.move_to(cpu_right_col_base[i - 5])
             ckpt_cpu_arr.append(a__)
         self.add(*a__			,    *a__)

         A__					=       Square(side_length=2.2)
         key.move_to([-5, 2, 0])

         A__					=       MarkupText(
             F"<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model"			,    font_size=1_8			,    )

         key_text.move_to([-5, 2.4, 0])

         self.add(a__			,    a__)

         A__					=       MarkupText(
             F"<span fgcolor='{BLUE}'>●</span> Checkpoint"			,    font_size=1_8			,    )

         blue_text.next_to(a__			,    DOWN * 2.4			,    aligned_edge=key_text.get_left())
         self.add(a__)

         A__					=       MarkupText(
             F"Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device."			,    font_size=2_4			,    )
         step_a.move_to([2, 2, 0])

         A__					=       [meta_mem.copy() for i in range(6)]
         A__					=       [meta_mem.copy() for i in range(6)]
         A__					=       VGroup(*a__).arrange(a__			,    buff=0)
         A__					=       VGroup(*a__).arrange(a__			,    buff=0)
         A__					=       VGroup(a__			,    a__).arrange(a__			,    buff=0)
         A__					=       Text('''Disk'''			,    font_size=2_4)
         A__					=       Group(a__			,    a__).arrange(a__			,    buff=0.5			,    aligned_edge=a__)
         disk.move_to([-4.0, -1.2_5, 0])
         self.play(Write(a__			,    run_time=3)			,    Write(a__			,    run_time=1)			,    Create(a__			,    run_time=1))

         A__					=       []
         for i, rect in enumerate(a__):
             A__					=       rect.copy()
             target.generate_target()
             target.target.move_to(disk_left_col_base[i]).scale(0.5)
             animations.append(MoveToTarget(a__			,    run_time=1.5))
         self.play(*a__)

         self.play(FadeOut(a__))

         A__					=       MarkupText(F"Then, the checkpoint is removed from memory\nthrough garbage collection."			,    font_size=2_4)
         step_a.move_to([2, 2, 0])

         self.play(Write(a__			,    run_time=3))

         self.play(
             FadeOut(a__			,    a__			,    *a__			,    *a__)			,    )

         self.wait()
