






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


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



class 				__UpperCAmelCase		(_UpperCAmelCase   ):







			def __init__(     self:  str				,     UpperCAmelCase_:  CLIPSegForImageSegmentation				,     UpperCAmelCase_:  CLIPSegProcessor				,     UpperCAmelCase_:  AutoencoderKL				,     UpperCAmelCase_:  CLIPTextModel				,     UpperCAmelCase_:  CLIPTokenizer				,     UpperCAmelCase_:  UNetaDConditionModel				,     UpperCAmelCase_:  Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]				,     UpperCAmelCase_:  StableDiffusionSafetyChecker				,     UpperCAmelCase_:  CLIPImageProcessor				,     ):







									'''simple docstring'''




									super().__init__()

									if hasattr(scheduler.config				,     """steps_offset"""					) and scheduler.config.steps_offset != 1:
															_SCREAMING_SNAKE_CASE     				=  (
															    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"""				,     UpperCAmelCase_				,     standard_warn=UpperCAmelCase_					)
															_SCREAMING_SNAKE_CASE     				=  dict(scheduler.config					)
															_SCREAMING_SNAKE_CASE     				=  1
															_SCREAMING_SNAKE_CASE     				=  FrozenDict(UpperCAmelCase_					)

									if hasattr(scheduler.config				,     """skip_prk_steps"""					) and scheduler.config.skip_prk_steps is False:
															_SCREAMING_SNAKE_CASE     				=  (
															    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"""				,     UpperCAmelCase_				,     standard_warn=UpperCAmelCase_					)
															_SCREAMING_SNAKE_CASE     				=  dict(scheduler.config					)
															_SCREAMING_SNAKE_CASE     				=  True
															_SCREAMING_SNAKE_CASE     				=  FrozenDict(UpperCAmelCase_					)

									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=UpperCAmelCase_				,     segmentation_processor=UpperCAmelCase_				,     vae=UpperCAmelCase_				,     text_encoder=UpperCAmelCase_				,     tokenizer=UpperCAmelCase_				,     unet=UpperCAmelCase_				,     scheduler=UpperCAmelCase_				,     safety_checker=UpperCAmelCase_				,     feature_extractor=UpperCAmelCase_				,     )







			def 							UpperCamelCase				(     self:  str				,     UpperCAmelCase_:  Optional[Union[str, int]] = "auto"					):







									'''simple docstring'''




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







			def 							UpperCamelCase				(     self:  Optional[Any]					):







									'''simple docstring'''




									self.enable_attention_slicing(UpperCAmelCase_					)







			def 							UpperCamelCase				(     self:  Union[str, Any]					):







									'''simple docstring'''




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

									_SCREAMING_SNAKE_CASE     				=  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(UpperCAmelCase_				,     UpperCAmelCase_					)







			@property
			# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
			def 							UpperCamelCase				(     self:  Tuple					):







									'''simple docstring'''




									if self.device != torch.device("""meta"""					) or not hasattr(self.unet				,     """_hf_hook"""					):
															return self.device
									for module in self.unet.modules():
															if (
															    hasattr(UpperCAmelCase_				,     """_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:  Tuple				,     UpperCAmelCase_:  Union[str, List[str]]				,     UpperCAmelCase_:  Union[torch.FloatTensor, PIL.Image.Image]				,     UpperCAmelCase_:  str				,     UpperCAmelCase_:  int = 512				,     UpperCAmelCase_:  int = 512				,     UpperCAmelCase_:  int = 50				,     UpperCAmelCase_:  float = 7.5				,     UpperCAmelCase_:  Optional[Union[str, List[str]]] = None				,     UpperCAmelCase_:  Optional[int] = 1				,     UpperCAmelCase_:  float = 0.0				,     UpperCAmelCase_:  Optional[torch.Generator] = None				,     UpperCAmelCase_:  Optional[torch.FloatTensor] = None				,     UpperCAmelCase_:  Optional[str] = "pil"				,     UpperCAmelCase_:  bool = True				,     UpperCAmelCase_:  Optional[Callable[[int, int, torch.FloatTensor], None]] = None				,     UpperCAmelCase_:  int = 1				,     **UpperCAmelCase_:  List[Any]				,     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  self.segmentation_processor(
									    text=[text]				,     images=[image]				,     padding="""max_length"""				,     return_tensors="""pt"""					).to(self.device					)
									_SCREAMING_SNAKE_CASE     				=  self.segmentation_model(**UpperCAmelCase_					)
									_SCREAMING_SNAKE_CASE     				=  torch.sigmoid(outputs.logits					).cpu().detach().unsqueeze(-1					).numpy()
									_SCREAMING_SNAKE_CASE     				=  self.numpy_to_pil(UpperCAmelCase_					)[0].resize(image.size					)

									# Run inpainting pipeline with the generated mask
									_SCREAMING_SNAKE_CASE     				=  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=UpperCAmelCase_				,     image=UpperCAmelCase_				,     mask_image=UpperCAmelCase_				,     height=UpperCAmelCase_				,     width=UpperCAmelCase_				,     num_inference_steps=UpperCAmelCase_				,     guidance_scale=UpperCAmelCase_				,     negative_prompt=UpperCAmelCase_				,     num_images_per_prompt=UpperCAmelCase_				,     eta=UpperCAmelCase_				,     generator=UpperCAmelCase_				,     latents=UpperCAmelCase_				,     output_type=UpperCAmelCase_				,     return_dict=UpperCAmelCase_				,     callback=UpperCAmelCase_				,     callback_steps=UpperCAmelCase_				,     )









from __future__ import annotations

import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
		import numpy
		import tensorflow as tf

		from transformers import (
		    TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
		    TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
		    TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
		    BertConfig,
		    DPRConfig,
		    TFDPRContextEncoder,
		    TFDPRQuestionEncoder,
		    TFDPRReader,
		)



class 				__UpperCAmelCase		:







			def __init__(     self:  Optional[int]				,     UpperCAmelCase_:  List[str]				,     UpperCAmelCase_:  int=13				,     UpperCAmelCase_:  List[str]=7				,     UpperCAmelCase_:  Union[str, Any]=True				,     UpperCAmelCase_:  List[str]=True				,     UpperCAmelCase_:  Dict=True				,     UpperCAmelCase_:  str=True				,     UpperCAmelCase_:  List[str]=99				,     UpperCAmelCase_:  int=32				,     UpperCAmelCase_:  List[Any]=2				,     UpperCAmelCase_:  Union[str, Any]=4				,     UpperCAmelCase_:  Dict=37				,     UpperCAmelCase_:  Tuple="gelu"				,     UpperCAmelCase_:  Any=0.1				,     UpperCAmelCase_:  List[str]=0.1				,     UpperCAmelCase_:  List[Any]=512				,     UpperCAmelCase_:  Optional[int]=16				,     UpperCAmelCase_:  Optional[Any]=2				,     UpperCAmelCase_:  Optional[int]=0.02				,     UpperCAmelCase_:  Union[str, Any]=3				,     UpperCAmelCase_:  Optional[int]=4				,     UpperCAmelCase_:  Tuple=None				,     UpperCAmelCase_:  Any=0				,     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  parent
									_SCREAMING_SNAKE_CASE     				=  batch_size
									_SCREAMING_SNAKE_CASE     				=  seq_length
									_SCREAMING_SNAKE_CASE     				=  is_training
									_SCREAMING_SNAKE_CASE     				=  use_input_mask
									_SCREAMING_SNAKE_CASE     				=  use_token_type_ids
									_SCREAMING_SNAKE_CASE     				=  use_labels
									_SCREAMING_SNAKE_CASE     				=  vocab_size
									_SCREAMING_SNAKE_CASE     				=  hidden_size
									_SCREAMING_SNAKE_CASE     				=  num_hidden_layers
									_SCREAMING_SNAKE_CASE     				=  num_attention_heads
									_SCREAMING_SNAKE_CASE     				=  intermediate_size
									_SCREAMING_SNAKE_CASE     				=  hidden_act
									_SCREAMING_SNAKE_CASE     				=  hidden_dropout_prob
									_SCREAMING_SNAKE_CASE     				=  attention_probs_dropout_prob
									_SCREAMING_SNAKE_CASE     				=  max_position_embeddings
									_SCREAMING_SNAKE_CASE     				=  type_vocab_size
									_SCREAMING_SNAKE_CASE     				=  type_sequence_label_size
									_SCREAMING_SNAKE_CASE     				=  initializer_range
									_SCREAMING_SNAKE_CASE     				=  num_labels
									_SCREAMING_SNAKE_CASE     				=  num_choices
									_SCREAMING_SNAKE_CASE     				=  scope
									_SCREAMING_SNAKE_CASE     				=  projection_dim







			def 							UpperCamelCase				(     self:  Any					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  ids_tensor([self.batch_size, self.seq_length]				,     self.vocab_size					)

									_SCREAMING_SNAKE_CASE     				=  None
									if self.use_input_mask:
															# follow test_modeling_tf_ctrl.py
															_SCREAMING_SNAKE_CASE     				=  random_attention_mask([self.batch_size, self.seq_length]					)

									_SCREAMING_SNAKE_CASE     				=  None
									if self.use_token_type_ids:
															_SCREAMING_SNAKE_CASE     				=  ids_tensor([self.batch_size, self.seq_length]				,     self.type_vocab_size					)

									_SCREAMING_SNAKE_CASE     				=  None
									_SCREAMING_SNAKE_CASE     				=  None
									_SCREAMING_SNAKE_CASE     				=  None
									if self.use_labels:
															_SCREAMING_SNAKE_CASE     				=  ids_tensor([self.batch_size]				,     self.type_sequence_label_size					)
															_SCREAMING_SNAKE_CASE     				=  ids_tensor([self.batch_size, self.seq_length]				,     self.num_labels					)
															_SCREAMING_SNAKE_CASE     				=  ids_tensor([self.batch_size]				,     self.num_choices					)

									_SCREAMING_SNAKE_CASE     				=  BertConfig(
									    vocab_size=self.vocab_size				,     hidden_size=self.hidden_size				,     num_hidden_layers=self.num_hidden_layers				,     num_attention_heads=self.num_attention_heads				,     intermediate_size=self.intermediate_size				,     hidden_act=self.hidden_act				,     hidden_dropout_prob=self.hidden_dropout_prob				,     attention_probs_dropout_prob=self.attention_probs_dropout_prob				,     max_position_embeddings=self.max_position_embeddings				,     type_vocab_size=self.type_vocab_size				,     is_decoder=UpperCAmelCase_				,     initializer_range=self.initializer_range				,     )
									_SCREAMING_SNAKE_CASE     				=  DPRConfig(projection_dim=self.projection_dim				,     **config.to_dict()					)

									return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels







			def 							UpperCamelCase				(     self:  Optional[int]				,     UpperCAmelCase_:  Optional[Any]				,     UpperCAmelCase_:  Any				,     UpperCAmelCase_:  int				,     UpperCAmelCase_:  List[str]				,     UpperCAmelCase_:  Dict				,     UpperCAmelCase_:  Dict				,     UpperCAmelCase_:  Any					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  TFDPRContextEncoder(config=UpperCAmelCase_					)
									_SCREAMING_SNAKE_CASE     				=  model(UpperCAmelCase_				,     attention_mask=UpperCAmelCase_				,     token_type_ids=UpperCAmelCase_					)
									_SCREAMING_SNAKE_CASE     				=  model(UpperCAmelCase_				,     token_type_ids=UpperCAmelCase_					)
									_SCREAMING_SNAKE_CASE     				=  model(UpperCAmelCase_					)
									self.parent.assertEqual(result.pooler_output.shape				,     (self.batch_size, self.projection_dim or self.hidden_size)					)







			def 							UpperCamelCase				(     self:  List[Any]				,     UpperCAmelCase_:  Union[str, Any]				,     UpperCAmelCase_:  Any				,     UpperCAmelCase_:  Dict				,     UpperCAmelCase_:  Union[str, Any]				,     UpperCAmelCase_:  Union[str, Any]				,     UpperCAmelCase_:  List[Any]				,     UpperCAmelCase_:  Any					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  TFDPRQuestionEncoder(config=UpperCAmelCase_					)
									_SCREAMING_SNAKE_CASE     				=  model(UpperCAmelCase_				,     attention_mask=UpperCAmelCase_				,     token_type_ids=UpperCAmelCase_					)
									_SCREAMING_SNAKE_CASE     				=  model(UpperCAmelCase_				,     token_type_ids=UpperCAmelCase_					)
									_SCREAMING_SNAKE_CASE     				=  model(UpperCAmelCase_					)
									self.parent.assertEqual(result.pooler_output.shape				,     (self.batch_size, self.projection_dim or self.hidden_size)					)







			def 							UpperCamelCase				(     self:  Optional[Any]				,     UpperCAmelCase_:  Dict				,     UpperCAmelCase_:  Optional[int]				,     UpperCAmelCase_:  List[Any]				,     UpperCAmelCase_:  str				,     UpperCAmelCase_:  Optional[Any]				,     UpperCAmelCase_:  Union[str, Any]				,     UpperCAmelCase_:  str					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  TFDPRReader(config=UpperCAmelCase_					)
									_SCREAMING_SNAKE_CASE     				=  model(UpperCAmelCase_				,     attention_mask=UpperCAmelCase_					)

									self.parent.assertEqual(result.start_logits.shape				,     (self.batch_size, self.seq_length)					)
									self.parent.assertEqual(result.end_logits.shape				,     (self.batch_size, self.seq_length)					)
									self.parent.assertEqual(result.relevance_logits.shape				,     (self.batch_size,)					)







			def 							UpperCamelCase				(     self:  Optional[int]					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  self.prepare_config_and_inputs()
									(
									    (
									    _SCREAMING_SNAKE_CASE
									)				,					(
									    _SCREAMING_SNAKE_CASE
									)				,					(
									    _SCREAMING_SNAKE_CASE
									)				,					(
									    _SCREAMING_SNAKE_CASE
									)				,					(
									    _SCREAMING_SNAKE_CASE
									)				,					(
									    _SCREAMING_SNAKE_CASE
									)				,					(
									    _SCREAMING_SNAKE_CASE
									)				,					
									)     				=  config_and_inputs
									_SCREAMING_SNAKE_CASE     				=  {"""input_ids""": input_ids}
									return config, inputs_dict



@require_tf
class 				__UpperCAmelCase		(_UpperCAmelCase	,_UpperCAmelCase	,unittest.TestCase   ):
			__snake_case    :				Dict									=							(
			    (
			        TFDPRContextEncoder,
			        TFDPRQuestionEncoder,
			        TFDPRReader,
			    )
			    if is_tf_available()
			    else ()
			)
			__snake_case    :				Optional[Any]									=							{"feature-extraction": TFDPRQuestionEncoder} if is_tf_available() else {}

			__snake_case    :				str									=							False
			__snake_case    :				List[Any]									=							False
			__snake_case    :				Any									=							False
			__snake_case    :				List[Any]									=							False
			__snake_case    :				Tuple									=							False







			def 							UpperCamelCase				(     self:  int					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  TFDPRModelTester(self					)
									_SCREAMING_SNAKE_CASE     				=  ConfigTester(self				,     config_class=UpperCAmelCase_				,     hidden_size=37					)







			def 							UpperCamelCase				(     self:  Any					):







									'''simple docstring'''




									self.config_tester.run_common_tests()







			def 							UpperCamelCase				(     self:  List[Any]					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_dpr_context_encoder(*UpperCAmelCase_					)







			def 							UpperCamelCase				(     self:  Optional[Any]					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_dpr_question_encoder(*UpperCAmelCase_					)







			def 							UpperCamelCase				(     self:  int					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_dpr_reader(*UpperCAmelCase_					)







			@slow
			def 							UpperCamelCase				(     self:  List[Any]					):







									'''simple docstring'''




									for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															_SCREAMING_SNAKE_CASE     				=  TFDPRContextEncoder.from_pretrained(UpperCAmelCase_					)
															self.assertIsNotNone(UpperCAmelCase_					)

									for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															_SCREAMING_SNAKE_CASE     				=  TFDPRContextEncoder.from_pretrained(UpperCAmelCase_					)
															self.assertIsNotNone(UpperCAmelCase_					)

									for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															_SCREAMING_SNAKE_CASE     				=  TFDPRQuestionEncoder.from_pretrained(UpperCAmelCase_					)
															self.assertIsNotNone(UpperCAmelCase_					)

									for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															_SCREAMING_SNAKE_CASE     				=  TFDPRReader.from_pretrained(UpperCAmelCase_					)
															self.assertIsNotNone(UpperCAmelCase_					)



@require_tf
class 				__UpperCAmelCase		(unittest.TestCase   ):







			@slow
			def 							UpperCamelCase				(     self:  Union[str, Any]					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base"""					)

									_SCREAMING_SNAKE_CASE     				=  tf.constant(
									    [[101, 7_592, 1_010, 2_003, 2_026, 3_899, 10_140, 1_029, 102]]					)  # [CLS] hello, is my dog cute? [SEP]
									_SCREAMING_SNAKE_CASE     				=  model(UpperCAmelCase_					)[0]  # embedding shape = (1, 768)
									# compare the actual values for a slice.
									_SCREAMING_SNAKE_CASE     				=  tf.constant(
									    [
									        [
									            0.03_23_62_53,
									            0.12_75_33_35,
									            0.16_81_85_09,
									            0.00_27_97_86,
									            0.3_89_69_33,
									            0.24_26_49_45,
									            0.2_17_89_71,
									            -0.02_33_52_27,
									            -0.08_48_19_59,
									            -0.14_32_41_17,
									        ]
									    ]					)
									self.assertTrue(numpy.allclose(output[:, :10].numpy()				,     expected_slice.numpy()				,     atol=1E-4					)					)

