


from typing import Callable, List, Optional, Union

import PIL
import torch
from transformers import (
    CLIPImageProcessor,
    CLIPSegForImageSegmentation,
    CLIPSegProcessor,
    CLIPTextModel,
    CLIPTokenizer,
)

from diffusers import DiffusionPipeline
from diffusers.configuration_utils import FrozenDict
from diffusers.models import AutoencoderKL, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
from diffusers.utils import deprecate, is_accelerate_available, logging


SCREAMING_SNAKE_CASE							    =							logging.get_logger(__name__)  # pylint: disable=invalid-name


class     __UpperCAmelCase							(       __A							):


     """simple docstring"""


     def __init__(	self  ,       __A  ,       __A  ,       __A  ,       __A  ,       __A  ,       __A  ,       __A  ,       __A  ,       __A  ,       ):
        super().__init__()

        if hasattr(scheduler.config  ,       """steps_offset"""    ) and scheduler.config.steps_offset != 1:
           __a					=  (
               f'''The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`'''
               f''' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure '''
               """to update the config accordingly as leaving `steps_offset` might led to incorrect results"""
               """ in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"""
               """ it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"""
               """ file"""
           )
           deprecate("""steps_offset!=1"""  ,       """1.0.0"""  ,       __A  ,       standard_warn=__A    )
           __a					=  dict(scheduler.config    )
           __a					=  1
           __a					=  FrozenDict(__A    )

        if hasattr(scheduler.config  ,       """skip_prk_steps"""    ) and scheduler.config.skip_prk_steps is False:
           __a					=  (
               f'''The configuration file of this scheduler: {scheduler} has not set the configuration'''
               """ `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make"""
               """ sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to"""
               """ incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face"""
               """ Hub, it would be very nice if you could open a Pull request for the"""
               """ `scheduler/scheduler_config.json` file"""
           )
           deprecate("""skip_prk_steps not set"""  ,       """1.0.0"""  ,       __A  ,       standard_warn=__A    )
           __a					=  dict(scheduler.config    )
           __a					=  True
           __a					=  FrozenDict(__A    )

        if safety_checker is None:
           logger.warning(
               f'''You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure'''
               """ that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"""
               """ results in services or applications open to the public. Both the diffusers team and Hugging Face"""
               """ strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"""
               """ it only for use-cases that involve analyzing network behavior or auditing its results. For more"""
               """ information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."""    )

        self.register_modules(
            segmentation_model=__A  ,       segmentation_processor=__A  ,       vae=__A  ,       text_encoder=__A  ,       tokenizer=__A  ,       unet=__A  ,       scheduler=__A  ,       safety_checker=__A  ,       feature_extractor=__A  ,       )


     def 	snake_case_  (	self  ,       __A = "auto"    ):
        if slice_size == "auto":
           # half the attention head size is usually a good trade-off between
           # speed and memory
           __a					=  self.unet.config.attention_head_dim // 2
        self.unet.set_attention_slice(__A    )


     def 	snake_case_  (	self    ):
        self.enable_attention_slicing(__A    )


     def 	snake_case_  (	self    ):
        if is_accelerate_available():
           from accelerate import cpu_offload
        else:
           raise ImportError("""Please install accelerate via `pip install accelerate`"""    )

        __a					=  torch.device("""cuda"""    )

        for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]:
           if cpu_offloaded_model is not None:
              cpu_offload(__A  ,       __A    )


     @property
     # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
     def 	snake_case_  (	self    ):
        if self.device != torch.device("""meta"""    ) or not hasattr(self.unet  ,       """_hf_hook"""    ):
           return self.device
        for module in self.unet.modules():
           if (
               hasattr(__A  ,       """_hf_hook"""    )
               and hasattr(module._hf_hook  ,       """execution_device"""    )
               and module._hf_hook.execution_device is not None
           ):
              return torch.device(module._hf_hook.execution_device    )
        return self.device


     @torch.no_grad()
     def __call__(	self  ,       __A  ,       __A  ,       __A  ,       __A = 512  ,       __A = 512  ,       __A = 50  ,       __A = 7.5  ,       __A = None  ,       __A = 1  ,       __A = 0.0  ,       __A = None  ,       __A = None  ,       __A = "pil"  ,       __A = True  ,       __A = None  ,       __A = 1  ,       **__A  ,       ):
        __a					=  self.segmentation_processor(
            text=[text]  ,       images=[image]  ,       padding="""max_length"""  ,       return_tensors="""pt"""    ).to(self.device    )
        __a					=  self.segmentation_model(**__A    )
        __a					=  torch.sigmoid(outputs.logits    ).cpu().detach().unsqueeze(-1    ).numpy()
        __a					=  self.numpy_to_pil(__A    )[0].resize(image.size    )

        # Run inpainting pipeline with the generated mask
        __a					=  StableDiffusionInpaintPipeline(
            vae=self.vae  ,       text_encoder=self.text_encoder  ,       tokenizer=self.tokenizer  ,       unet=self.unet  ,       scheduler=self.scheduler  ,       safety_checker=self.safety_checker  ,       feature_extractor=self.feature_extractor  ,       )
        return inpainting_pipeline(
            prompt=__A  ,       image=__A  ,       mask_image=__A  ,       height=__A  ,       width=__A  ,       num_inference_steps=__A  ,       guidance_scale=__A  ,       negative_prompt=__A  ,       num_images_per_prompt=__A  ,       eta=__A  ,       generator=__A  ,       latents=__A  ,       output_type=__A  ,       return_dict=__A  ,       callback=__A  ,       callback_steps=__A  ,       )








from __future__ import annotations

import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import is_tf_available, is_vision_available

from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_tf_bert import TFBertModelTester
from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester
from ..deit.test_modeling_tf_deit import TFDeiTModelTester
from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester
from ..vit.test_modeling_tf_vit import TFViTModelTester


if is_tf_available():
   from transformers import (
       TFBertModel,
       TFCLIPVisionModel,
       TFDeiTModel,
       TFRobertaModel,
       TFVisionTextDualEncoderModel,
       TFViTModel,
       VisionTextDualEncoderConfig,
   )

if is_vision_available():
   from PIL import Image

   from transformers import VisionTextDualEncoderProcessor



def 		lowerCAmelCase__     (       UpperCamelCase_					:							List[Any]						)->	Dict:
    if isinstance(UpperCamelCase_			,							collections.abc.Iterable						):
        return x
    return (x, x)



@require_tf
class      _UpperCAmelCase      :




     def 		snake_case_		(					self			,    a__			,    a__):
         pass




     def 		snake_case_		(					self):
         pass




     def 		snake_case_		(					self):
         pass




     def 		snake_case_		(					self			,    a__			,    a__			,    a__			,    a__			,    a__=None			,    **a__):
         A__					=       VisionTextDualEncoderConfig.from_vision_text_configs(a__			,    a__)

         A__					=       TFVisionTextDualEncoderModel(a__)

         A__					=       model(input_ids=a__			,    pixel_values=a__			,    attention_mask=a__)

         self.assertEqual(output['''text_embeds'''].shape			,    (input_ids.shape[0], config.projection_dim))
         self.assertEqual(output['''image_embeds'''].shape			,    (pixel_values.shape[0], config.projection_dim))




     def 		snake_case_		(					self			,    a__			,    a__			,    a__			,    a__			,    a__=None			,    **a__):
         A__			,						A__					=       self.get_vision_text_model(a__			,    a__)
         A__					=       TFVisionTextDualEncoderModel(vision_model=a__			,    text_model=a__)

         A__					=       model(input_ids=a__			,    pixel_values=a__			,    attention_mask=a__)

         self.assertEqual(output['''text_embeds'''].shape			,    (input_ids.shape[0], model.config.projection_dim))
         self.assertEqual(output['''image_embeds'''].shape			,    (pixel_values.shape[0], model.config.projection_dim))




     def 		snake_case_		(					self			,    a__			,    a__			,    a__			,    a__			,    a__=None			,    **a__):
         A__			,						A__					=       self.get_vision_text_model(a__			,    a__)
         A__					=       {'''vision_model''': vision_model, '''text_model''': text_model}
         A__					=       TFVisionTextDualEncoderModel.from_vision_text_pretrained(**a__)

         A__					=       model(input_ids=a__			,    pixel_values=a__			,    attention_mask=a__)

         self.assertEqual(output['''text_embeds'''].shape			,    (input_ids.shape[0], model.config.projection_dim))
         self.assertEqual(output['''image_embeds'''].shape			,    (pixel_values.shape[0], model.config.projection_dim))




     def 		snake_case_		(					self			,    a__			,    a__			,    a__			,    a__			,    a__=None			,    **a__):
         A__			,						A__					=       self.get_vision_text_model(a__			,    a__)
         A__					=       TFVisionTextDualEncoderModel(vision_model=a__			,    text_model=a__)

         A__					=       model(input_ids=a__			,    pixel_values=a__			,    attention_mask=a__)
         A__					=       output[0].numpy()

         with tempfile.TemporaryDirectory() as tmpdirname:
             model.save_pretrained(a__)
             A__					=       TFVisionTextDualEncoderModel.from_pretrained(a__)

             A__					=       model(input_ids=a__			,    pixel_values=a__			,    attention_mask=a__)
             A__					=       after_output[0].numpy()
             A__					=       np.amax(np.abs(out_a - out_a))
             self.assertLessEqual(a__			,    1e-5)




     def 		snake_case_		(					self			,    a__			,    a__			,    a__			,    a__			,    a__=None			,    **a__):
         A__			,						A__					=       self.get_vision_text_model(a__			,    a__)
         A__					=       TFVisionTextDualEncoderModel(vision_model=a__			,    text_model=a__)

         A__					=       model(
             input_ids=a__			,    pixel_values=a__			,    attention_mask=a__			,    output_attentions=a__)

         A__					=       output.vision_model_output.attentions
         self.assertEqual(len(a__)			,    vision_config.num_hidden_layers)

         # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
         A__					=       to_atuple(vision_model.config.image_size)
         A__					=       to_atuple(vision_model.config.patch_size)
         A__					=       (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
         A__					=       num_patches + 1
         self.assertEqual(vision_attentions[0].shape[-3:]			,    (vision_config.num_attention_heads, seq_len, seq_len))

         A__					=       output.text_model_output.attentions
         self.assertEqual(len(a__)			,    text_config.num_hidden_layers)

         self.assertEqual(
             text_attentions[0].shape[-3:]			,    (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])			,    )




     def 		snake_case_		(					self			,    a__			,    a__			,    a__):
         A__					=       np.abs((a - b)).max()
         self.assertLessEqual(a__			,    a__			,    F"Difference between torch and flax is {diff} (>= {tol}).")




     def 		snake_case_		(					self):
         A__					=       self.prepare_config_and_inputs()
         self.check_vision_text_dual_encoder_model(**a__)




     def 		snake_case_		(					self):
         A__					=       self.prepare_config_and_inputs()
         self.check_model_from_pretrained_configs(**a__)




     def 		snake_case_		(					self):
         A__					=       self.prepare_config_and_inputs()
         self.check_vision_text_dual_encoder_from_pretrained(**a__)




     def 		snake_case_		(					self):
         A__					=       self.prepare_config_and_inputs()
         self.check_save_load(**a__)




     def 		snake_case_		(					self):
         A__					=       self.prepare_config_and_inputs()
         self.check_vision_text_output_attention(**a__)




     @slow
     def 		snake_case_		(					self):
         A__			,						A__					=       self.get_pretrained_model_and_inputs()

         A__					=       model_a(**a__)
         A__					=       outputs[0].numpy()

         with tempfile.TemporaryDirectory() as tmp_dirname:
             model_a.save_pretrained(a__)
             A__					=       TFVisionTextDualEncoderModel.from_pretrained(a__)

             A__					=       model_a(**a__)
             A__					=       after_outputs[0].numpy()
             A__					=       np.amax(np.abs(out_a - out_a))
             self.assertLessEqual(a__			,    1e-5)







@require_tf
class      _UpperCAmelCase      (							A__      ,   unittest.TestCase  ):




     def 		snake_case_		(					self):
         A__					=       TFVisionTextDualEncoderModel.from_vision_text_pretrained(
             '''hf-internal-testing/tiny-random-vit'''			,    '''hf-internal-testing/tiny-random-bert''')
         A__					=       1_3
         A__					=       floats_tensor(
             [
                 batch_size,
                 model.vision_model.config.num_channels,
                 model.vision_model.config.image_size,
                 model.vision_model.config.image_size,
             ])
         A__					=       ids_tensor([batch_size, 4]			,    model.text_model.config.vocab_size)
         A__					=       random_attention_mask([batch_size, 4])
         A__					=       {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}

         return model, inputs




     def 		snake_case_		(					self			,    a__			,    a__):
         A__					=       TFViTModel(a__			,    name='''vision_model''')
         A__					=       TFBertModel(a__			,    name='''text_model''')
         return vision_model, text_model




     def 		snake_case_		(					self):
         A__					=       TFViTModelTester(self)
         A__					=       TFBertModelTester(self)
         A__					=       vit_model_tester.prepare_config_and_inputs()
         A__					=       bert_model_tester.prepare_config_and_inputs()

         A__			,						A__			,						A__					=       vision_config_and_inputs

         (
             (
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						
         )					=       text_config_and_inputs

         return {
             "text_config": text_config,
             "vision_config": vision_config,
             "pixel_values": pixel_values,
             "attention_mask": input_mask,
             "input_ids": input_ids,
             "text_token_type_ids": token_type_ids,
             "text_sequence_labels": sequence_labels,
             "text_token_labels": token_labels,
             "text_choice_labels": choice_labels,
         }







@require_tf
class      _UpperCAmelCase      (							A__      ,   unittest.TestCase  ):




     def 		snake_case_		(					self):
         # DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's
         # just reinitialize it.
         A__					=       TFVisionTextDualEncoderModel.from_vision_text_pretrained(
             '''Rocketknight1/tiny-random-deit-tf'''			,    '''hf-internal-testing/tiny-random-roberta''')
         A__					=       1_3
         A__					=       floats_tensor(
             [
                 batch_size,
                 model.vision_model.config.num_channels,
                 model.vision_model.config.image_size,
                 model.vision_model.config.image_size,
             ])
         A__					=       ids_tensor([batch_size, 4]			,    model.text_model.config.vocab_size)
         A__					=       random_attention_mask([batch_size, 4])
         A__					=       {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}

         return model, inputs




     def 		snake_case_		(					self			,    a__			,    a__			,    a__			,    a__			,    a__=None			,    **a__):
         A__			,						A__					=       self.get_vision_text_model(a__			,    a__)
         A__					=       TFVisionTextDualEncoderModel(vision_model=a__			,    text_model=a__)

         A__					=       model(
             input_ids=a__			,    pixel_values=a__			,    attention_mask=a__			,    output_attentions=a__)

         A__					=       output.vision_model_output.attentions
         self.assertEqual(len(a__)			,    vision_config.num_hidden_layers)

         # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
         A__					=       to_atuple(vision_model.config.image_size)
         A__					=       to_atuple(vision_model.config.patch_size)
         A__					=       (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
         A__					=       num_patches + 2
         self.assertEqual(vision_attentions[0].shape[-3:]			,    (vision_config.num_attention_heads, seq_len, seq_len))

         A__					=       output.text_model_output.attentions
         self.assertEqual(len(a__)			,    text_config.num_hidden_layers)

         self.assertEqual(
             text_attentions[0].shape[-3:]			,    (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])			,    )




     def 		snake_case_		(					self			,    a__			,    a__):
         A__					=       TFDeiTModel(a__			,    name='''vision_model''')
         A__					=       TFRobertaModel(a__			,    name='''text_model''')
         return vision_model, text_model




     def 		snake_case_		(					self):
         A__					=       TFDeiTModelTester(self)
         A__					=       TFRobertaModelTester(self)
         A__					=       vit_model_tester.prepare_config_and_inputs()
         A__					=       bert_model_tester.prepare_config_and_inputs()

         A__			,						A__			,						A__					=       vision_config_and_inputs

         (
             (
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						
         )					=       text_config_and_inputs

         return {
             "text_config": text_config,
             "vision_config": vision_config,
             "pixel_values": pixel_values,
             "attention_mask": input_mask,
             "input_ids": input_ids,
             "text_token_type_ids": token_type_ids,
             "text_sequence_labels": sequence_labels,
             "text_token_labels": token_labels,
             "text_choice_labels": choice_labels,
         }







@require_tf
class      _UpperCAmelCase      (							A__      ,   unittest.TestCase  ):




     def 		snake_case_		(					self):
         A__					=       TFVisionTextDualEncoderModel.from_vision_text_pretrained(
             '''Rocketknight1/tiny-random-clip-tf'''			,    '''hf-internal-testing/tiny-random-bert''')
         A__					=       1_3
         A__					=       floats_tensor(
             [
                 batch_size,
                 model.vision_model.config.num_channels,
                 model.vision_model.config.image_size,
                 model.vision_model.config.image_size,
             ])
         A__					=       ids_tensor([batch_size, 4]			,    model.text_model.config.vocab_size)
         A__					=       random_attention_mask([batch_size, 4])
         A__					=       {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}

         return model, inputs




     def 		snake_case_		(					self			,    a__			,    a__):
         A__					=       TFCLIPVisionModel(a__			,    name='''vision_model''')
         A__					=       TFBertModel(a__			,    name='''text_model''')
         return vision_model, text_model




     def 		snake_case_		(					self):
         A__					=       TFCLIPVisionModelTester(self)
         A__					=       TFBertModelTester(self)
         A__					=       clip_model_tester.prepare_config_and_inputs()
         A__					=       bert_model_tester.prepare_config_and_inputs()

         A__			,						A__					=       vision_config_and_inputs

         (
             (
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						
         )					=       text_config_and_inputs

         return {
             "text_config": text_config,
             "vision_config": vision_config,
             "pixel_values": pixel_values,
             "attention_mask": input_mask,
             "input_ids": input_ids,
             "text_token_type_ids": token_type_ids,
             "text_sequence_labels": sequence_labels,
             "text_token_labels": token_labels,
             "text_choice_labels": choice_labels,
         }







@require_vision
@require_tf
class      _UpperCAmelCase      (							unittest.TestCase  ):




     @slow
     def 		snake_case_		(					self):
         A__					=       TFVisionTextDualEncoderModel.from_pretrained(
             '''clip-italian/clip-italian'''			,    logit_scale_init_value=1.0			,    from_pt=a__)
         A__					=       VisionTextDualEncoderProcessor.from_pretrained('''clip-italian/clip-italian''')

         A__					=       Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''')
         A__					=       processor(
             text=['''una foto di un gatto''', '''una foto di un cane''']			,    images=a__			,    padding=a__			,    return_tensors='''np''')

         A__					=       model(**a__)

         # verify the logits
         self.assertEqual(outputs.logits_per_image.shape			,    (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]))
         self.assertEqual(
             outputs.logits_per_text.shape			,    (inputs.input_ids.shape[0], inputs.pixel_values.shape[0])			,    )

         A__					=       np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]])

         self.assertTrue(np.allclose(outputs.logits_per_image.numpy()			,    a__			,    atol=1e-3))
