




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 				UpperCamelCase_    ( UpperCAmelCase__		,					UpperCAmelCase__		,					UpperCAmelCase__		,					unittest.TestCase     ):

    '''simple docstring'''






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


    def        SCREAMING_SNAKE_CASE							(			self      :	List[str])						->Optional[Any]:





           '''simple docstring'''

           torch.manual_seed(0)
           A__       =    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=UpperCAmelCase__					, )
           A__       =    PNDMScheduler(skip_prk_steps=UpperCAmelCase__)
           torch.manual_seed(0)
           A__       =    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)
           A__       =    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=1_000					, hidden_act='''gelu'''					, projection_dim=512					, )
           A__       =    CLIPTextModel(UpperCAmelCase__)
           A__       =    CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''')

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


    def        SCREAMING_SNAKE_CASE							(			self      :	List[Any]					, UpperCAmelCase__      :	Any					, UpperCAmelCase__      :	List[Any]=0)						->Optional[Any]:





           '''simple docstring'''

           A__       =    floats_tensor((1, 3, 32, 32)					, rng=random.Random(UpperCAmelCase__)).to(UpperCAmelCase__)
           A__       =    image.cpu().permute(0					, 2					, 3					, 1)[0]
           A__       =    Image.fromarray(np.uinta(UpperCAmelCase__)).convert('''RGB''').resize((64, 64))
           A__       =    Image.fromarray(np.uinta(image + 4)).convert('''RGB''').resize((64, 64))
           if str(UpperCAmelCase__).startswith('''mps'''):
                  A__       =    torch.manual_seed(UpperCAmelCase__)
           else:
                  A__       =    torch.Generator(device=UpperCAmelCase__).manual_seed(UpperCAmelCase__)
           A__       =    {
               '''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        SCREAMING_SNAKE_CASE							(			self      :	Dict)						->List[Any]:





           '''simple docstring'''

           A__       =    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
           A__       =    self.get_dummy_components()
           A__       =    StableDiffusionInpaintPipeline(**UpperCAmelCase__)
           A__       =    sd_pipe.to(UpperCAmelCase__)
           sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__)

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

           assert image.shape == (1, 64, 64, 3)
           A__       =    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        SCREAMING_SNAKE_CASE							(			self      :	int)						->Dict:





           '''simple docstring'''

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


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

    '''simple docstring'''






    def        SCREAMING_SNAKE_CASE							(			self      :	Tuple)						->int:





           '''simple docstring'''

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


    def        SCREAMING_SNAKE_CASE							(			self      :	Optional[int])						->int:





           '''simple docstring'''

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

           A__       =    '''stabilityai/stable-diffusion-2-inpainting'''
           A__       =    StableDiffusionInpaintPipeline.from_pretrained(UpperCAmelCase__					, safety_checker=UpperCAmelCase__)
           pipe.to(UpperCAmelCase__)
           pipe.set_progress_bar_config(disable=UpperCAmelCase__)
           pipe.enable_attention_slicing()

           A__       =    '''Face of a yellow cat, high resolution, sitting on a park bench'''

           A__       =    torch.manual_seed(0)
           A__       =    pipe(
               prompt=UpperCAmelCase__					, image=UpperCAmelCase__					, mask_image=UpperCAmelCase__					, generator=UpperCAmelCase__					, output_type='''np'''					, )
           A__       =    output.images[0]

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


    def        SCREAMING_SNAKE_CASE							(			self      :	Optional[int])						->Dict:





           '''simple docstring'''

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

           A__       =    '''stabilityai/stable-diffusion-2-inpainting'''
           A__       =    StableDiffusionInpaintPipeline.from_pretrained(
               UpperCAmelCase__					, torch_dtype=torch.floataa					, safety_checker=UpperCAmelCase__					, )
           pipe.to(UpperCAmelCase__)
           pipe.set_progress_bar_config(disable=UpperCAmelCase__)
           pipe.enable_attention_slicing()

           A__       =    '''Face of a yellow cat, high resolution, sitting on a park bench'''

           A__       =    torch.manual_seed(0)
           A__       =    pipe(
               prompt=UpperCAmelCase__					, image=UpperCAmelCase__					, mask_image=UpperCAmelCase__					, generator=UpperCAmelCase__					, output_type='''np'''					, )
           A__       =    output.images[0]

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





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





           '''simple docstring'''

           torch.cuda.empty_cache()
           torch.cuda.reset_max_memory_allocated()
           torch.cuda.reset_peak_memory_stats()

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

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

           A__       =    '''Face of a yellow cat, high resolution, sitting on a park bench'''

           A__       =    torch.manual_seed(0)
           A__       =    pipe(
               prompt=UpperCAmelCase__					, image=UpperCAmelCase__					, mask_image=UpperCAmelCase__					, generator=UpperCAmelCase__					, num_inference_steps=2					, output_type='''np'''					, )

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








import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_lowerCamelCase	:		Tuple							       =   logging.get_logger(__name__)

_lowerCamelCase	:		str							       =   {
    """microsoft/git-base""": """https://huggingface.co/microsoft/git-base/resolve/main/config.json""",
}


class 				UpperCamelCase_    ( UpperCAmelCase__     ):

    '''simple docstring'''






    UpperCAmelCase__							  =      '''git_vision_model'''


    def __init__(			self      :	Any					, UpperCAmelCase__      :	Any=768					, UpperCAmelCase__      :	int=3_072					, UpperCAmelCase__      :	List[str]=12					, UpperCAmelCase__      :	Dict=12					, UpperCAmelCase__      :	Optional[int]=3					, UpperCAmelCase__      :	List[Any]=224					, UpperCAmelCase__      :	Union[str, Any]=16					, UpperCAmelCase__      :	Union[str, Any]="quick_gelu"					, UpperCAmelCase__      :	Dict=1e-5					, UpperCAmelCase__      :	Union[str, Any]=0.0					, UpperCAmelCase__      :	Any=0.02					, **UpperCAmelCase__      :	Any					, )						->Optional[int]:





           '''simple docstring'''

           super().__init__(**UpperCAmelCase__)

           A__       =    hidden_size
           A__       =    intermediate_size
           A__       =    num_hidden_layers
           A__       =    num_attention_heads
           A__       =    num_channels
           A__       =    patch_size
           A__       =    image_size
           A__       =    initializer_range
           A__       =    attention_dropout
           A__       =    layer_norm_eps
           A__       =    hidden_act





    @classmethod
    def        SCREAMING_SNAKE_CASE							(			cls      :	Any					, UpperCAmelCase__      :	Union[str, os.PathLike]					, **UpperCAmelCase__      :	int)						->"PretrainedConfig":





           '''simple docstring'''

           cls._set_token_in_kwargs(UpperCAmelCase__)

           A__ ,							A__       =    cls.get_config_dict(UpperCAmelCase__					, **UpperCAmelCase__)

           # get the vision config dict if we are loading from GITConfig
           if config_dict.get('''model_type''') == "git":
                  A__       =    config_dict['''vision_config''']

           if "model_type" in config_dict and hasattr(cls					, '''model_type''') and config_dict["model_type"] != cls.model_type:
                  logger.warning(
                      f"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """
                      f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""")

           return cls.from_dict(UpperCAmelCase__					, **UpperCAmelCase__)


class 				UpperCamelCase_    ( UpperCAmelCase__     ):

    '''simple docstring'''






    UpperCAmelCase__							  =      '''git'''


    def __init__(			self      :	Dict					, UpperCAmelCase__      :	Dict=None					, UpperCAmelCase__      :	int=30_522					, UpperCAmelCase__      :	Optional[int]=768					, UpperCAmelCase__      :	Dict=6					, UpperCAmelCase__      :	int=12					, UpperCAmelCase__      :	List[str]=3_072					, UpperCAmelCase__      :	str="gelu"					, UpperCAmelCase__      :	int=0.1					, UpperCAmelCase__      :	Union[str, Any]=0.1					, UpperCAmelCase__      :	List[Any]=1_024					, UpperCAmelCase__      :	List[str]=0.02					, UpperCAmelCase__      :	Any=1e-12					, UpperCAmelCase__      :	Union[str, Any]=0					, UpperCAmelCase__      :	List[Any]="absolute"					, UpperCAmelCase__      :	int=True					, UpperCAmelCase__      :	Any=False					, UpperCAmelCase__      :	int=101					, UpperCAmelCase__      :	Tuple=102					, UpperCAmelCase__      :	Dict=None					, **UpperCAmelCase__      :	List[str]					, )						->Any:





           '''simple docstring'''

           super().__init__(bos_token_id=UpperCAmelCase__					, eos_token_id=UpperCAmelCase__					, pad_token_id=UpperCAmelCase__					, **UpperCAmelCase__)

           if vision_config is None:
                  A__       =    {}
                  logger.info('''vision_config is None. initializing the GitVisionConfig with default values.''')

           A__       =    GitVisionConfig(**UpperCAmelCase__)
           A__       =    vocab_size
           A__       =    hidden_size
           A__       =    num_hidden_layers
           A__       =    num_attention_heads
           A__       =    hidden_act
           A__       =    intermediate_size
           A__       =    hidden_dropout_prob
           A__       =    attention_probs_dropout_prob
           A__       =    max_position_embeddings
           A__       =    initializer_range
           A__       =    layer_norm_eps
           A__       =    position_embedding_type
           A__       =    use_cache
           A__       =    tie_word_embeddings
           A__       =    num_image_with_embedding

           A__       =    bos_token_id
           A__       =    eos_token_id





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





           '''simple docstring'''

           A__       =    copy.deepcopy(self.__dict__)
           A__       =    self.vision_config.to_dict()
           A__       =    self.__class__.model_type
           return output


