


import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()
class 	lowerCamelCase_       (				lowerCAmelCase__     ,     unittest.TestCase				):



					'''simple docstring'''







					__UpperCAmelCase            =				KandinskyInpaintPipeline
					__UpperCAmelCase            =				["prompt", "image_embeds", "negative_image_embeds", "image", "mask_image"]
					__UpperCAmelCase            =				[
					    "prompt",
					    "negative_prompt",
					    "image_embeds",
					    "negative_image_embeds",
					    "image",
					    "mask_image",
					]
					__UpperCAmelCase            =				[
					    "generator",
					    "height",
					    "width",
					    "latents",
					    "guidance_scale",
					    "negative_prompt",
					    "num_inference_steps",
					    "return_dict",
					    "guidance_scale",
					    "num_images_per_prompt",
					    "output_type",
					    "return_dict",
					]
					__UpperCAmelCase            =				False






					@property
					def A      (				self						)   ->			Any:







								'''simple docstring'''

								return 3_2






					@property
					def A      (				self						)   ->			int:







								'''simple docstring'''

								return 3_2






					@property
					def A      (				self						)   ->			List[Any]:







								'''simple docstring'''

								return self.time_input_dim






					@property
					def A      (				self						)   ->			List[str]:







								'''simple docstring'''

								return self.time_input_dim * 4






					@property
					def A      (				self						)   ->			Optional[Any]:







								'''simple docstring'''

								return 1_0_0






					@property
					def A      (				self						)   ->			int:







								'''simple docstring'''

								__lowercase 					=   XLMRobertaTokenizerFast.from_pretrained('''YiYiXu/tiny-random-mclip-base'''						)
								return tokenizer






					@property
					def A      (				self						)   ->			Any:







								'''simple docstring'''

								torch.manual_seed(0						)
								__lowercase 					=   MCLIPConfig(
								    numDims=self.cross_attention_dim ,       transformerDimensions=self.text_embedder_hidden_size ,       hidden_size=self.text_embedder_hidden_size ,       intermediate_size=3_7 ,       num_attention_heads=4 ,       num_hidden_layers=5 ,       vocab_size=1_0_0_5 ,       )

								__lowercase 					=   MultilingualCLIP(snake_case_						)
								__lowercase 					=   text_encoder.eval()

								return text_encoder






					@property
					def A      (				self						)   ->			Optional[Any]:







								'''simple docstring'''

								torch.manual_seed(0						)

								__lowercase 					=   {
								    '''in_channels''': 9,
								    # Out channels is double in channels because predicts mean and variance
								    '''out_channels''': 8,
								    '''addition_embed_type''': '''text_image''',
								    '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''),
								    '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''),
								    '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''',
								    '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2),
								    '''layers_per_block''': 1,
								    '''encoder_hid_dim''': self.text_embedder_hidden_size,
								    '''encoder_hid_dim_type''': '''text_image_proj''',
								    '''cross_attention_dim''': self.cross_attention_dim,
								    '''attention_head_dim''': 4,
								    '''resnet_time_scale_shift''': '''scale_shift''',
								    '''class_embed_type''': None,
								}

								__lowercase 					=   UNetaDConditionModel(**snake_case_						)
								return model






					@property
					def A      (				self						)   ->			str:







								'''simple docstring'''

								return {
								    "block_out_channels": [3_2, 6_4],
								    "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
								    "in_channels": 3,
								    "latent_channels": 4,
								    "layers_per_block": 1,
								    "norm_num_groups": 8,
								    "norm_type": "spatial",
								    "num_vq_embeddings": 1_2,
								    "out_channels": 3,
								    "up_block_types": [
								        "AttnUpDecoderBlock2D",
								        "UpDecoderBlock2D",
								    ],
								    "vq_embed_dim": 4,
								}






					@property
					def A      (				self						)   ->			Any:







								'''simple docstring'''

								torch.manual_seed(0						)
								__lowercase 					=   VQModel(**self.dummy_movq_kwargs						)
								return model






					def A      (				self						)   ->			int:







								'''simple docstring'''

								__lowercase 					=   self.dummy_text_encoder
								__lowercase 					=   self.dummy_tokenizer
								__lowercase 					=   self.dummy_unet
								__lowercase 					=   self.dummy_movq

								__lowercase 					=   DDIMScheduler(
								    num_train_timesteps=1_0_0_0 ,       beta_schedule='''linear''' ,       beta_start=0.0_0_0_8_5 ,       beta_end=0.0_1_2 ,       clip_sample=snake_case_ ,       set_alpha_to_one=snake_case_ ,       steps_offset=1 ,       prediction_type='''epsilon''' ,       thresholding=snake_case_ ,       )

								__lowercase 					=   {
								    '''text_encoder''': text_encoder,
								    '''tokenizer''': tokenizer,
								    '''unet''': unet,
								    '''scheduler''': scheduler,
								    '''movq''': movq,
								}

								return components






					def A      (				self ,       snake_case_ ,       snake_case_=0						)   ->			int:







								'''simple docstring'''

								__lowercase 					=   floats_tensor((1, self.cross_attention_dim) ,       rng=random.Random(snake_case_						)						).to(snake_case_						)
								__lowercase 					=   floats_tensor((1, self.cross_attention_dim) ,       rng=random.Random(seed + 1						)						).to(snake_case_						)
								# create init_image
								__lowercase 					=   floats_tensor((1, 3, 6_4, 6_4) ,       rng=random.Random(snake_case_						)						).to(snake_case_						)
								__lowercase 					=   image.cpu().permute(0 ,       2 ,       3 ,       1						)[0]
								__lowercase 					=   Image.fromarray(np.uinta(snake_case_						)						).convert('''RGB'''						).resize((2_5_6, 2_5_6)						)
								# create mask
								__lowercase 					=   np.ones((6_4, 6_4) ,       dtype=np.floataa						)
								__lowercase 					=   0

								if str(snake_case_						).startswith('''mps'''						):
											__lowercase 					=   torch.manual_seed(snake_case_						)
								else:
											__lowercase 					=   torch.Generator(device=snake_case_						).manual_seed(snake_case_						)
								__lowercase 					=   {
								    '''prompt''': '''horse''',
								    '''image''': init_image,
								    '''mask_image''': mask,
								    '''image_embeds''': image_embeds,
								    '''negative_image_embeds''': negative_image_embeds,
								    '''generator''': generator,
								    '''height''': 6_4,
								    '''width''': 6_4,
								    '''num_inference_steps''': 2,
								    '''guidance_scale''': 4.0,
								    '''output_type''': '''np''',
								}
								return inputs






					def A      (				self						)   ->			Any:







								'''simple docstring'''

								__lowercase 					=   '''cpu'''

								__lowercase 					=   self.get_dummy_components()

								__lowercase 					=   self.pipeline_class(**snake_case_						)
								__lowercase 					=   pipe.to(snake_case_						)

								pipe.set_progress_bar_config(disable=snake_case_						)

								__lowercase 					=   pipe(**self.get_dummy_inputs(snake_case_						)						)
								__lowercase 					=   output.images

								__lowercase 					=   pipe(
								    **self.get_dummy_inputs(snake_case_						) ,       return_dict=snake_case_ ,       )[0]

								__lowercase 					=   image[0, -3:, -3:, -1]
								__lowercase 					=   image_from_tuple[0, -3:, -3:, -1]

								print(F'image.shape {image.shape}'						)

								assert image.shape == (1, 6_4, 6_4, 3)

								__lowercase 					=   np.array(
								    [0.8_3_2_6_9_1_9, 0.7_3_7_9_0_4_6_7, 0.2_0_9_1_8_5_8_1, 0.9_3_0_9_6_1_2, 0.5_5_1_1_7_9_1, 0.4_3_7_1_3_3_2_8, 0.5_5_1_3_3_2_1, 0.4_9_9_2_2_9_3_4, 0.5_9_4_9_7_7_8_6]						)

								assert (
								    np.abs(image_slice.flatten() - expected_slice						).max() < 1e-2
								), F' expected_slice {expected_slice}, but got {image_slice.flatten()}'
								assert (
								    np.abs(image_from_tuple_slice.flatten() - expected_slice						).max() < 1e-2
								), F' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}'






					def A      (				self						)   ->			List[str]:







								'''simple docstring'''

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




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



					'''simple docstring'''







					def A      (				self						)   ->			Any:







								'''simple docstring'''

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






					def A      (				self						)   ->			Any:







								'''simple docstring'''

								__lowercase 					=   load_numpy(
								    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
								    '''/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy'''						)

								__lowercase 					=   load_image(
								    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png'''						)
								__lowercase 					=   np.ones((7_6_8, 7_6_8) ,       dtype=np.floataa						)
								__lowercase 					=   0

								__lowercase 					=   '''a hat'''

								__lowercase 					=   KandinskyPriorPipeline.from_pretrained(
								    '''kandinsky-community/kandinsky-2-1-prior''' ,       torch_dtype=torch.floataa						)
								pipe_prior.to(snake_case_						)

								__lowercase 					=   KandinskyInpaintPipeline.from_pretrained(
								    '''kandinsky-community/kandinsky-2-1-inpaint''' ,       torch_dtype=torch.floataa						)
								__lowercase 					=   pipeline.to(snake_case_						)
								pipeline.set_progress_bar_config(disable=snake_case_						)

								__lowercase 					=   torch.Generator(device='''cpu'''						).manual_seed(0						)
								__lowercase					, __lowercase 					=   pipe_prior(
								    snake_case_ ,       generator=snake_case_ ,       num_inference_steps=5 ,       negative_prompt='''''' ,       ).to_tuple()

								__lowercase 					=   pipeline(
								    snake_case_ ,       image=snake_case_ ,       mask_image=snake_case_ ,       image_embeds=snake_case_ ,       negative_image_embeds=snake_case_ ,       generator=snake_case_ ,       num_inference_steps=1_0_0 ,       height=7_6_8 ,       width=7_6_8 ,       output_type='''np''' ,       )

								__lowercase 					=   output.images[0]

								assert image.shape == (7_6_8, 7_6_8, 3)

								assert_mean_pixel_difference(snake_case_ ,       snake_case_						)






import copy
import os
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union


if TYPE_CHECKING:
	from ...processing_utils import ProcessorMixin
	from ...utils import TensorType

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


a : Union[str, Any]		=				logging.get_logger(__name__)

a : Any		=				{
    '''google/owlvit-base-patch32''': '''https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json''',
    '''google/owlvit-base-patch16''': '''https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json''',
    '''google/owlvit-large-patch14''': '''https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json''',
}
class 	lowerCamelCase_       (				lowerCAmelCase__				):



					'''simple docstring'''







					__UpperCAmelCase            =				"owlvit_text_model"






					def __init__(				self ,       snake_case_=4_9_4_0_8 ,       snake_case_=5_1_2 ,       snake_case_=2_0_4_8 ,       snake_case_=1_2 ,       snake_case_=8 ,       snake_case_=1_6 ,       snake_case_="quick_gelu" ,       snake_case_=1e-5 ,       snake_case_=0.0 ,       snake_case_=0.0_2 ,       snake_case_=1.0 ,       snake_case_=0 ,       snake_case_=4_9_4_0_6 ,       snake_case_=4_9_4_0_7 ,       **snake_case_ ,       )   ->			int:







								'''simple docstring'''

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

								__lowercase 					=   vocab_size
								__lowercase 					=   hidden_size
								__lowercase 					=   intermediate_size
								__lowercase 					=   num_hidden_layers
								__lowercase 					=   num_attention_heads
								__lowercase 					=   max_position_embeddings
								__lowercase 					=   hidden_act
								__lowercase 					=   layer_norm_eps
								__lowercase 					=   attention_dropout
								__lowercase 					=   initializer_range
								__lowercase 					=   initializer_factor






					@classmethod
					def A      (				cls ,       snake_case_ ,       **snake_case_						)   ->			"PretrainedConfig":







								'''simple docstring'''

								cls._set_token_in_kwargs(snake_case_						)

								__lowercase					, __lowercase 					=   cls.get_config_dict(snake_case_ ,       **snake_case_						)

								# get the text config dict if we are loading from OwlViTConfig
								if config_dict.get('''model_type'''						) == "owlvit":
											__lowercase 					=   config_dict['''text_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(snake_case_ ,       **snake_case_						)




class 	lowerCamelCase_       (				lowerCAmelCase__				):



					'''simple docstring'''







					__UpperCAmelCase            =				"owlvit_vision_model"






					def __init__(				self ,       snake_case_=7_6_8 ,       snake_case_=3_0_7_2 ,       snake_case_=1_2 ,       snake_case_=1_2 ,       snake_case_=3 ,       snake_case_=7_6_8 ,       snake_case_=3_2 ,       snake_case_="quick_gelu" ,       snake_case_=1e-5 ,       snake_case_=0.0 ,       snake_case_=0.0_2 ,       snake_case_=1.0 ,       **snake_case_ ,       )   ->			Any:







								'''simple docstring'''

								super().__init__(**snake_case_						)

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






					@classmethod
					def A      (				cls ,       snake_case_ ,       **snake_case_						)   ->			"PretrainedConfig":







								'''simple docstring'''

								cls._set_token_in_kwargs(snake_case_						)

								__lowercase					, __lowercase 					=   cls.get_config_dict(snake_case_ ,       **snake_case_						)

								# get the vision config dict if we are loading from OwlViTConfig
								if config_dict.get('''model_type'''						) == "owlvit":
											__lowercase 					=   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(snake_case_ ,       **snake_case_						)




class 	lowerCamelCase_       (				lowerCAmelCase__				):



					'''simple docstring'''







					__UpperCAmelCase            =				"owlvit"
					__UpperCAmelCase            =				True






					def __init__(				self ,       snake_case_=None ,       snake_case_=None ,       snake_case_=5_1_2 ,       snake_case_=2.6_5_9_2 ,       snake_case_=True ,       **snake_case_ ,       )   ->			Optional[Any]:







								'''simple docstring'''

								super().__init__(**snake_case_						)

								if text_config is None:
											__lowercase 					=   {}
											logger.info('''text_config is None. Initializing the OwlViTTextConfig with default values.'''						)

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

								__lowercase 					=   OwlViTTextConfig(**snake_case_						)
								__lowercase 					=   OwlViTVisionConfig(**snake_case_						)

								__lowercase 					=   projection_dim
								__lowercase 					=   logit_scale_init_value
								__lowercase 					=   return_dict
								__lowercase 					=   1.0






					@classmethod
					def A      (				cls ,       snake_case_ ,       **snake_case_						)   ->			"PretrainedConfig":







								'''simple docstring'''

								cls._set_token_in_kwargs(snake_case_						)

								__lowercase					, __lowercase 					=   cls.get_config_dict(snake_case_ ,       **snake_case_						)

								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(snake_case_ ,       **snake_case_						)






					@classmethod
					def A      (				cls ,       snake_case_ ,       snake_case_ ,       **snake_case_						)   ->			int:







								'''simple docstring'''

								__lowercase 					=   {}
								__lowercase 					=   text_config
								__lowercase 					=   vision_config

								return cls.from_dict(snake_case_ ,       **snake_case_						)






					def A      (				self						)   ->			Any:







								'''simple docstring'''

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




class 	lowerCamelCase_       (				lowerCAmelCase__				):



					'''simple docstring'''







					@property
					def A      (				self						)   ->			Mapping[str, Mapping[int, str]]:







								'''simple docstring'''

								return OrderedDict(
								    [
								        ('''input_ids''', {0: '''batch''', 1: '''sequence'''}),
								        ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
								        ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}),
								    ]						)






					@property
					def A      (				self						)   ->			Mapping[str, Mapping[int, str]]:







								'''simple docstring'''

								return OrderedDict(
								    [
								        ('''logits_per_image''', {0: '''batch'''}),
								        ('''logits_per_text''', {0: '''batch'''}),
								        ('''text_embeds''', {0: '''batch'''}),
								        ('''image_embeds''', {0: '''batch'''}),
								    ]						)






					@property
					def A      (				self						)   ->			float:







								'''simple docstring'''

								return 1e-4






					def A      (				self ,       snake_case_ ,       snake_case_ = -1 ,       snake_case_ = -1 ,       snake_case_ = None ,       )   ->			Mapping[str, Any]:







								'''simple docstring'''

								__lowercase 					=   super().generate_dummy_inputs(
								    processor.tokenizer ,       batch_size=snake_case_ ,       seq_length=snake_case_ ,       framework=snake_case_						)
								__lowercase 					=   super().generate_dummy_inputs(
								    processor.image_processor ,       batch_size=snake_case_ ,       framework=snake_case_						)
								return {**text_input_dict, **image_input_dict}






					@property
					def A      (				self						)   ->			int:







								'''simple docstring'''

								return 1_4


