



import random
import unittest

import torch

from diffusers import IFInpaintingSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin





@skip_mps
class    lowerCamelCase__  (						UpperCAmelCase_       ,    UpperCAmelCase_       ,    unittest.TestCase):
     """simple docstring"""



     _A       =			IFInpaintingSuperResolutionPipeline
     _A       =			TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'width', 'height'}
     _A       =			TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({'original_image'})
     _A       =			PipelineTesterMixin.required_optional_params - {'latents'}







     def 						_a      (self    ):






           '''simple docstring'''



           return self._get_superresolution_dummy_components()







     def 						_a      (self				,			__a				,			__a=0    ):






           '''simple docstring'''



           if str(__a    ).startswith("mps"    ):
                 lowerCamelCase								=		torch.manual_seed(__a    )
           else:
                 lowerCamelCase								=		torch.Generator(device=__a    ).manual_seed(__a    )

           lowerCamelCase								=		floats_tensor((1, 3, 16, 16)				,			rng=random.Random(__a    )    ).to(__a    )
           lowerCamelCase								=		floats_tensor((1, 3, 32, 32)				,			rng=random.Random(__a    )    ).to(__a    )
           lowerCamelCase								=		floats_tensor((1, 3, 32, 32)				,			rng=random.Random(__a    )    ).to(__a    )

           lowerCamelCase								=		{
               "prompt": "A painting of a squirrel eating a burger",
               "image": image,
               "original_image": original_image,
               "mask_image": mask_image,
               "generator": generator,
               "num_inference_steps": 2,
               "output_type": "numpy",
           }

           return inputs







     @unittest.skipIf(
         torch_device != "cuda" or not is_xformers_available()				,			reason="XFormers attention is only available with CUDA and `xformers` installed"				,			)
     def 						_a      (self    ):






           '''simple docstring'''



           self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3    )







     def 						_a      (self    ):






           '''simple docstring'''



           self._test_save_load_optional_components()







     @unittest.skipIf(torch_device != "cuda"				,			reason="float16 requires CUDA"    )
     def 						_a      (self    ):






           '''simple docstring'''



           super().test_save_load_floataa(expected_max_diff=1E-1    )







     def 						_a      (self    ):






           '''simple docstring'''



           self._test_attention_slicing_forward_pass(expected_max_diff=1E-2    )







     def 						_a      (self    ):






           '''simple docstring'''



           self._test_save_load_local()







     def 						_a      (self    ):






           '''simple docstring'''



           self._test_inference_batch_single_identical(
               expected_max_diff=1E-2				,			)




import numpy as np
import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModelWithProjection, PreTrainedModel

from ...utils import logging


a_						:     Tuple	     =		logging.get_logger(__name__)





class    lowerCamelCase__  (						UpperCAmelCase_):
     """simple docstring"""



     _A       =			CLIPConfig

     _A       =			['CLIPEncoderLayer']







     def __init__(self				,			__a    ):






           '''simple docstring'''



           super().__init__(__a    )

           lowerCamelCase								=		CLIPVisionModelWithProjection(config.vision_config    )

           lowerCamelCase								=		nn.Linear(config.vision_config.projection_dim				,			1    )
           lowerCamelCase								=		nn.Linear(config.vision_config.projection_dim				,			1    )







     @torch.no_grad()
     def 						_a      (self				,			__a				,			__a				,			__a=0.5				,			__a=0.5    ):






           '''simple docstring'''



           lowerCamelCase								=		self.vision_model(__a    )[0]

           lowerCamelCase								=		self.p_head(__a    )
           lowerCamelCase								=		nsfw_detected.flatten()
           lowerCamelCase								=		nsfw_detected > p_threshold
           lowerCamelCase								=		nsfw_detected.tolist()

           if any(__a    ):
                 logger.warning(
                     "Potential NSFW content was detected in one or more images. A black image will be returned instead."
                     " Try again with a different prompt and/or seed."    )

           for idx, nsfw_detected_ in enumerate(__a    ):
                 if nsfw_detected_:
                       lowerCamelCase								=		np.zeros(images[idx].shape    )

           lowerCamelCase								=		self.w_head(__a    )
           lowerCamelCase								=		watermark_detected.flatten()
           lowerCamelCase								=		watermark_detected > w_threshold
           lowerCamelCase								=		watermark_detected.tolist()

           if any(__a    ):
                 logger.warning(
                     "Potential watermarked content was detected in one or more images. A black image will be returned instead."
                     " Try again with a different prompt and/or seed."    )

           for idx, watermark_detected_ in enumerate(__a    ):
                 if watermark_detected_:
                       lowerCamelCase								=		np.zeros(images[idx].shape    )

           return images, nsfw_detected, watermark_detected