




'''simple docstring'''

from typing import List, Optional, Union

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

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)


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

a    :							Optional[Any]										=    '\n    Examples:\n        ```py\n        >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline\n        >>> from diffusers.utils import load_image\n        >>> import torch\n\n        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n        ...     "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n        ... )\n        >>> pipe_prior.to("cuda")\n\n        >>> prompt = "A red cartoon frog, 4k"\n        >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)\n\n        >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(\n        ...     "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16\n        ... )\n        >>> pipe.to("cuda")\n\n        >>> init_image = load_image(\n        ...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n        ...     "/kandinsky/frog.png"\n        ... )\n\n        >>> image = pipe(\n        ...     image=init_image,\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=zero_image_emb,\n        ...     height=768,\n        ...     width=768,\n        ...     num_inference_steps=100,\n        ...     strength=0.2,\n        ... ).images\n\n        >>> image[0].save("red_frog.png")\n        ```\n'


def 						__magic_name__       (      __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase=8      )						->   Tuple:

					'''simple docstring'''

					snake_case_		     =							height // scale_factor**2
					if height % scale_factor**2 != 0:
										new_height += 1
					snake_case_		     =							width // scale_factor**2
					if width % scale_factor**2 != 0:
										new_width += 1
					return new_height * scale_factor, new_width * scale_factor


def 						__magic_name__       (      __UpperCAmelCase, __UpperCAmelCase=512, __UpperCAmelCase=512      )						->   Optional[Any]:

					'''simple docstring'''

					snake_case_		     =							pil_image.resize((w, h), resample=Image.BICUBIC, reducing_gap=1      )
					snake_case_		     =							np.array(pil_image.convert('''RGB'''      )      )
					snake_case_		     =							arr.astype(np.floataa      ) / 1_2_7.5 - 1
					snake_case_		     =							np.transpose(__UpperCAmelCase, [2, 0, 1]      )
					snake_case_		     =							torch.from_numpy(__UpperCAmelCase      ).unsqueeze(0      )
					return image






class 		a							(  _lowerCamelCase	):


				def __init__(						self       :   List[Any]			,							lowercase_       :   UNetaDConditionModel			,							lowercase_       :   DDPMScheduler			,							lowercase_       :   VQModel			,							):
									super().__init__()

									self.register_modules(
									    unet=lowercase_			,							scheduler=lowercase_			,							movq=lowercase_			,							)
									snake_case_		     =							2 ** (len(self.movq.config.block_out_channels   ) - 1)


				def     A_					(						self       :   int			,							lowercase_       :   List[Any]			,							lowercase_       :   Tuple			,							lowercase_       :   Optional[int]   ):
									# get the original timestep using init_timestep
									snake_case_		     =							min(int(num_inference_steps * strength   )			,							lowercase_   )

									snake_case_		     =							max(num_inference_steps - init_timestep			,							0   )
									snake_case_		     =							self.scheduler.timesteps[t_start:]

									return timesteps, num_inference_steps - t_start


				def     A_					(						self       :   int			,							lowercase_       :   int			,							lowercase_       :   int			,							lowercase_       :   Tuple			,							lowercase_       :   Union[str, Any]			,							lowercase_       :   Optional[Any]			,							lowercase_       :   Optional[int]			,							lowercase_       :   List[Any]=None   ):
									if not isinstance(lowercase_			,							(torch.Tensor, PIL.Image.Image, list)   ):
														raise ValueError(
														    F"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(lowercase_   )}"   )

									snake_case_		     =							image.to(device=lowercase_			,							dtype=lowercase_   )

									snake_case_		     =							batch_size * num_images_per_prompt

									if image.shape[1] == 4:
														snake_case_		     =							image

									else:
														if isinstance(lowercase_			,							lowercase_   ) and len(lowercase_   ) != batch_size:
																			raise ValueError(
																			    F"You have passed a list of generators of length {len(lowercase_   )}, but requested an effective batch"
																			    F" size of {batch_size}. Make sure the batch size matches the length of the generators."   )

														elif isinstance(lowercase_			,							lowercase_   ):
																			snake_case_		     =							[
																			    self.movq.encode(image[i : i + 1]   ).latent_dist.sample(generator[i]   ) for i in range(lowercase_   )
																			]
																			snake_case_		     =							torch.cat(lowercase_			,							dim=0   )
														else:
																			snake_case_		     =							self.movq.encode(lowercase_   ).latent_dist.sample(lowercase_   )

														snake_case_		     =							self.movq.config.scaling_factor * init_latents

									snake_case_		     =							torch.cat([init_latents]			,							dim=0   )

									snake_case_		     =							init_latents.shape
									snake_case_		     =							randn_tensor(lowercase_			,							generator=lowercase_			,							device=lowercase_			,							dtype=lowercase_   )

									# get latents
									snake_case_		     =							self.scheduler.add_noise(lowercase_			,							lowercase_			,							lowercase_   )

									snake_case_		     =							init_latents

									return latents


				def     A_					(						self       :   str			,							lowercase_       :   List[str]=0   ):
									if is_accelerate_available():
														from accelerate import cpu_offload
									else:
														raise ImportError('''Please install accelerate via `pip install accelerate`'''   )

									snake_case_		     =							torch.device(F"cuda:{gpu_id}"   )

									snake_case_		     =							[
									    self.unet,
									    self.movq,
									]
									for cpu_offloaded_model in models:
														if cpu_offloaded_model is not None:
																			cpu_offload(lowercase_			,							lowercase_   )


				def     A_					(						self       :   Tuple			,							lowercase_       :   Optional[Any]=0   ):
									if is_accelerate_available() and is_accelerate_version('''>='''			,							'''0.17.0.dev0'''   ):
														from accelerate import cpu_offload_with_hook
									else:
														raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.'''   )

									snake_case_		     =							torch.device(F"cuda:{gpu_id}"   )

									if self.device.type != "cpu":
														self.to('''cpu'''			,							silence_dtype_warnings=lowercase_   )
														torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

									snake_case_		     =							None
									for cpu_offloaded_model in [self.unet, self.movq]:
														snake_case_     ,snake_case_		     =							cpu_offload_with_hook(lowercase_			,							lowercase_			,							prev_module_hook=lowercase_   )

									# We'll offload the last model manually.
									snake_case_		     =							hook


				@property
				# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
				def     A_					(						self       :   List[str]   ):
									if not hasattr(self.unet			,							'''_hf_hook'''   ):
														return self.device
									for module in self.unet.modules():
														if (
														    hasattr(lowercase_			,							'''_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()
				@replace_example_docstring(lowercase_   )
				def __call__(						self       :   Dict			,							lowercase_       :   Union[torch.FloatTensor, List[torch.FloatTensor]]			,							lowercase_       :   Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]]			,							lowercase_       :   Union[torch.FloatTensor, List[torch.FloatTensor]]			,							lowercase_       :   int = 512			,							lowercase_       :   int = 512			,							lowercase_       :   int = 100			,							lowercase_       :   float = 4.0			,							lowercase_       :   float = 0.3			,							lowercase_       :   int = 1			,							lowercase_       :   Optional[Union[torch.Generator, List[torch.Generator]]] = None			,							lowercase_       :   Optional[str] = "pil"			,							lowercase_       :   bool = True			,							):
									snake_case_		     =							self._execution_device

									snake_case_		     =							guidance_scale > 1.0

									if isinstance(lowercase_			,							lowercase_   ):
														snake_case_		     =							torch.cat(lowercase_			,							dim=0   )
									snake_case_		     =							image_embeds.shape[0]
									if isinstance(lowercase_			,							lowercase_   ):
														snake_case_		     =							torch.cat(lowercase_			,							dim=0   )

									if do_classifier_free_guidance:
														snake_case_		     =							image_embeds.repeat_interleave(lowercase_			,							dim=0   )
														snake_case_		     =							negative_image_embeds.repeat_interleave(lowercase_			,							dim=0   )

									snake_case_		     =							torch.cat([negative_image_embeds, image_embeds]			,							dim=0   ).to(dtype=self.unet.dtype			,							device=lowercase_   )

									if not isinstance(lowercase_			,							lowercase_   ):
														snake_case_		     =							[image]
									if not all(isinstance(lowercase_			,							(PIL.Image.Image, torch.Tensor)   ) for i in image   ):
														raise ValueError(
														    F"Input is in incorrect format: {[type(lowercase_   ) for i in image]}. Currently, we only support  PIL image and pytorch tensor"   )

									snake_case_		     =							torch.cat([prepare_image(lowercase_			,							lowercase_			,							lowercase_   ) for i in image]			,							dim=0   )
									snake_case_		     =							image.to(dtype=image_embeds.dtype			,							device=lowercase_   )

									snake_case_		     =							self.movq.encode(lowercase_   )['''latents''']
									snake_case_		     =							latents.repeat_interleave(lowercase_			,							dim=0   )
									self.scheduler.set_timesteps(lowercase_			,							device=lowercase_   )
									snake_case_     ,snake_case_		     =							self.get_timesteps(lowercase_			,							lowercase_			,							lowercase_   )
									snake_case_		     =							timesteps[:1].repeat(batch_size * num_images_per_prompt   )
									snake_case_     ,snake_case_		     =							downscale_height_and_width(lowercase_			,							lowercase_			,							self.movq_scale_factor   )
									snake_case_		     =							self.prepare_latents(
									    lowercase_			,							lowercase_			,							lowercase_			,							lowercase_			,							image_embeds.dtype			,							lowercase_			,							lowercase_   )
									for i, t in enumerate(self.progress_bar(lowercase_   )   ):
														# expand the latents if we are doing classifier free guidance
														snake_case_		     =							torch.cat([latents] * 2   ) if do_classifier_free_guidance else latents

														snake_case_		     =							{'''image_embeds''': image_embeds}
														snake_case_		     =							self.unet(
														    sample=lowercase_			,							timestep=lowercase_			,							encoder_hidden_states=lowercase_			,							added_cond_kwargs=lowercase_			,							return_dict=lowercase_			,							)[0]

														if do_classifier_free_guidance:
																			snake_case_     ,snake_case_		     =							noise_pred.split(latents.shape[1]			,							dim=1   )
																			snake_case_     ,snake_case_		     =							noise_pred.chunk(2   )
																			snake_case_     ,snake_case_		     =							variance_pred.chunk(2   )
																			snake_case_		     =							noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
																			snake_case_		     =							torch.cat([noise_pred, variance_pred_text]			,							dim=1   )

														if not (
														    hasattr(self.scheduler.config			,							'''variance_type'''   )
														    and self.scheduler.config.variance_type in ["learned", "learned_range"]
														):
																			snake_case_     ,snake_case_		     =							noise_pred.split(latents.shape[1]			,							dim=1   )

														# compute the previous noisy sample x_t -> x_t-1
														snake_case_		     =							self.scheduler.step(
														    lowercase_			,							lowercase_			,							lowercase_			,							generator=lowercase_			,							)[0]

									# post-processing
									snake_case_		     =							self.movq.decode(lowercase_			,							force_not_quantize=lowercase_   )['''sample''']

									if output_type not in ["pt", "np", "pil"]:
														raise ValueError(F"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}"   )

									if output_type in ["np", "pil"]:
														snake_case_		     =							image * 0.5 + 0.5
														snake_case_		     =							image.clamp(0			,							1   )
														snake_case_		     =							image.cpu().permute(0			,							2			,							3			,							1   ).float().numpy()

									if output_type == "pil":
														snake_case_		     =							self.numpy_to_pil(lowercase_   )

									if not return_dict:
														return (image,)

									return ImagePipelineOutput(images=lowercase_   )







'''simple docstring'''

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 		a							:


				def __init__(						self       :   Any			,							lowercase_       :   int			,							lowercase_       :   str=13			,							lowercase_       :   Union[str, Any]=7			,							lowercase_       :   Any=True			,							lowercase_       :   List[str]=True			,							lowercase_       :   Tuple=True			,							lowercase_       :   List[Any]=True			,							lowercase_       :   str=99			,							lowercase_       :   int=32			,							lowercase_       :   int=2			,							lowercase_       :   Any=4			,							lowercase_       :   Union[str, Any]=37			,							lowercase_       :   Optional[int]="gelu"			,							lowercase_       :   Dict=0.1			,							lowercase_       :   Optional[Any]=0.1			,							lowercase_       :   Union[str, Any]=512			,							lowercase_       :   Dict=16			,							lowercase_       :   int=2			,							lowercase_       :   Any=0.02			,							lowercase_       :   int=3			,							lowercase_       :   Any=4			,							lowercase_       :   List[Any]=None			,							lowercase_       :   List[str]=0			,							):
									snake_case_		     =							parent
									snake_case_		     =							batch_size
									snake_case_		     =							seq_length
									snake_case_		     =							is_training
									snake_case_		     =							use_input_mask
									snake_case_		     =							use_token_type_ids
									snake_case_		     =							use_labels
									snake_case_		     =							vocab_size
									snake_case_		     =							hidden_size
									snake_case_		     =							num_hidden_layers
									snake_case_		     =							num_attention_heads
									snake_case_		     =							intermediate_size
									snake_case_		     =							hidden_act
									snake_case_		     =							hidden_dropout_prob
									snake_case_		     =							attention_probs_dropout_prob
									snake_case_		     =							max_position_embeddings
									snake_case_		     =							type_vocab_size
									snake_case_		     =							type_sequence_label_size
									snake_case_		     =							initializer_range
									snake_case_		     =							num_labels
									snake_case_		     =							num_choices
									snake_case_		     =							scope
									snake_case_		     =							projection_dim


				def     A_					(						self       :   int   ):
									snake_case_		     =							ids_tensor([self.batch_size, self.seq_length]			,							self.vocab_size   )

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

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

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

									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=lowercase_			,							initializer_range=self.initializer_range			,							)
									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     A_					(						self       :   Dict			,							lowercase_       :   Optional[Any]			,							lowercase_       :   int			,							lowercase_       :   Optional[int]			,							lowercase_       :   int			,							lowercase_       :   int			,							lowercase_       :   Union[str, Any]			,							lowercase_       :   str   ):
									snake_case_		     =							TFDPRContextEncoder(config=lowercase_   )
									snake_case_		     =							model(lowercase_			,							attention_mask=lowercase_			,							token_type_ids=lowercase_   )
									snake_case_		     =							model(lowercase_			,							token_type_ids=lowercase_   )
									snake_case_		     =							model(lowercase_   )
									self.parent.assertEqual(result.pooler_output.shape			,							(self.batch_size, self.projection_dim or self.hidden_size)   )


				def     A_					(						self       :   Any			,							lowercase_       :   Optional[Any]			,							lowercase_       :   List[str]			,							lowercase_       :   Union[str, Any]			,							lowercase_       :   Dict			,							lowercase_       :   Dict			,							lowercase_       :   Dict			,							lowercase_       :   Any   ):
									snake_case_		     =							TFDPRQuestionEncoder(config=lowercase_   )
									snake_case_		     =							model(lowercase_			,							attention_mask=lowercase_			,							token_type_ids=lowercase_   )
									snake_case_		     =							model(lowercase_			,							token_type_ids=lowercase_   )
									snake_case_		     =							model(lowercase_   )
									self.parent.assertEqual(result.pooler_output.shape			,							(self.batch_size, self.projection_dim or self.hidden_size)   )


				def     A_					(						self       :   str			,							lowercase_       :   Tuple			,							lowercase_       :   Tuple			,							lowercase_       :   Tuple			,							lowercase_       :   Tuple			,							lowercase_       :   Tuple			,							lowercase_       :   Dict			,							lowercase_       :   Dict   ):
									snake_case_		     =							TFDPRReader(config=lowercase_   )
									snake_case_		     =							model(lowercase_			,							attention_mask=lowercase_   )

									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     A_					(						self       :   Union[str, Any]   ):
									snake_case_		     =							self.prepare_config_and_inputs()
									(
									    (
									    snake_case_
									)     ,(
									    snake_case_
									)     ,(
									    snake_case_
									)     ,(
									    snake_case_
									)     ,(
									    snake_case_
									)     ,(
									    snake_case_
									)     ,(
									    snake_case_
									)     ,
									)		     =							config_and_inputs
									snake_case_		     =							{'''input_ids''': input_ids}
									return config, inputs_dict







@require_tf
class 		a							(  _lowerCamelCase  ,	_lowerCamelCase  ,	unittest.TestCase	):
				snake_case_           =						(
				    (
				        TFDPRContextEncoder,
				        TFDPRQuestionEncoder,
				        TFDPRReader,
				    )
				    if is_tf_available()
				    else ()
				)
				snake_case_           =						{"feature-extraction": TFDPRQuestionEncoder} if is_tf_available() else {}

				snake_case_           =						False
				snake_case_           =						False
				snake_case_           =						False
				snake_case_           =						False
				snake_case_           =						False


				def     A_					(						self       :   List[Any]   ):
									snake_case_		     =							TFDPRModelTester(self   )
									snake_case_		     =							ConfigTester(self			,							config_class=lowercase_			,							hidden_size=37   )


				def     A_					(						self       :   Any   ):
									self.config_tester.run_common_tests()


				def     A_					(						self       :   int   ):
									snake_case_		     =							self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_dpr_context_encoder(*lowercase_   )


				def     A_					(						self       :   List[Any]   ):
									snake_case_		     =							self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_dpr_question_encoder(*lowercase_   )


				def     A_					(						self       :   Any   ):
									snake_case_		     =							self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_dpr_reader(*lowercase_   )


				@slow
				def     A_					(						self       :   int   ):
									for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														snake_case_		     =							TFDPRContextEncoder.from_pretrained(lowercase_   )
														self.assertIsNotNone(lowercase_   )

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

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

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







@require_tf
class 		a							(  unittest.TestCase	):


				@slow
				def     A_					(						self       :   Dict   ):
									snake_case_		     =							TFDPRQuestionEncoder.from_pretrained('''facebook/dpr-question_encoder-single-nq-base'''   )

									snake_case_		     =							tf.constant(
									    [[101, 7592, 1010, 2003, 2026, 3899, 1_0140, 1029, 102]]   )  # [CLS] hello, is my dog cute? [SEP]
									snake_case_		     =							model(lowercase_   )[0]  # embedding shape = (1, 768)
									# compare the actual values for a slice.
									snake_case_		     =							tf.constant(
									    [
									        [
									            0.0323_6253,
									            0.1275_3335,
									            0.1681_8509,
									            0.0027_9786,
									            0.389_6933,
									            0.2426_4945,
									            0.217_8971,
									            -0.0233_5227,
									            -0.0848_1959,
									            -0.1432_4117,
									        ]
									    ]   )
									self.assertTrue(numpy.allclose(output[:, :10].numpy()			,							expected_slice.numpy()			,							atol=1e-4   )   )

