




'''simple docstring'''





from typing import Any, Dict, List, Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, ChunkPipeline


if is_vision_available():
		from PIL import Image

		from ..image_utils import load_image

if is_torch_available():
		import torch

		from transformers.modeling_outputs import BaseModelOutput

		from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING

_SCREAMING_SNAKE_CASE							:       List[Any]						=			logging.get_logger(__name__)




@add_end_docstrings(lowercase_							)
class 			_snake_case		(     lowercase_							):




			def __init__( self    ,							**a__							)    ->    Any:

										'''simple docstring'''




										super().__init__(**a__							)

										if self.framework == "tf":
																	raise ValueError(F'The {self.__class__} is only available in PyTorch.'							)

										requires_backends(self    ,							"vision"							)
										self.check_model_type(a__							)




			def __call__( self    ,							a__    ,							a__ = None    ,							**a__    ,							)    ->    Optional[int]:

										'''simple docstring'''




										if "text_queries" in kwargs:
																	snake_case_      =				kwargs.pop("text_queries"							)

										if isinstance(a__    ,							(str, Image.Image)							):
																	snake_case_      =				{"image": image, "candidate_labels": candidate_labels}
										else:
																	snake_case_      =				image
										snake_case_      =				super().__call__(a__    ,							**a__							)
										return results




			def        lowerCAmelCase__    ( self    ,							**a__							)    ->    int:

										'''simple docstring'''




										snake_case_      =				{}
										if "threshold" in kwargs:
																	snake_case_      =				kwargs["threshold"]
										if "top_k" in kwargs:
																	snake_case_      =				kwargs["top_k"]
										return {}, {}, postprocess_params




			def        lowerCAmelCase__    ( self    ,							a__							)    ->    int:

										'''simple docstring'''




										snake_case_      =				load_image(inputs["image"]							)
										snake_case_      =				inputs["candidate_labels"]
										if isinstance(a__    ,							a__							):
																	snake_case_      =				candidate_labels.split(","							)

										snake_case_      =				torch.tensor([[image.height, image.width]]    ,							dtype=torch.intaa							)
										for i, candidate_label in enumerate(a__							):
																	snake_case_      =				self.tokenizer(a__    ,							return_tensors=self.framework							)
																	snake_case_      =				self.image_processor(a__    ,							return_tensors=self.framework							)
																	yield {
																	    "is_last": i == len(a__							) - 1,
																	    "target_size": target_size,
																	    "candidate_label": candidate_label,
																	    **text_inputs,
																	    **image_features,
																	}




			def        lowerCAmelCase__    ( self    ,							a__							)    ->    Union[str, Any]:

										'''simple docstring'''




										snake_case_      =				model_inputs.pop("target_size"							)
										snake_case_      =				model_inputs.pop("candidate_label"							)
										snake_case_      =				model_inputs.pop("is_last"							)

										snake_case_      =				self.model(**a__							)

										snake_case_      =				{"target_size": target_size, "candidate_label": candidate_label, "is_last": is_last, **outputs}
										return model_outputs




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__=0.1    ,							a__=None							)    ->    Tuple:

										'''simple docstring'''




										snake_case_      =				[]
										for model_output in model_outputs:
																	snake_case_      =				model_output["candidate_label"]
																	snake_case_      =				BaseModelOutput(a__							)
																	snake_case_      =				self.image_processor.post_process_object_detection(
																	    outputs=a__    ,							threshold=a__    ,							target_sizes=model_output["target_size"]							)[0]

																	for index in outputs["scores"].nonzero():
																								snake_case_      =				outputs["scores"][index].item()
																								snake_case_      =				self._get_bounding_box(outputs["boxes"][index][0]							)

																								snake_case_      =				{"score": score, "label": label, "box": box}
																								results.append(a__							)

										snake_case_      =				sorted(a__    ,							key=lambda a__							: x["score"]    ,							reverse=a__							)
										if top_k:
																	snake_case_      =				results[:top_k]

										return results




			def        lowerCAmelCase__    ( self    ,							a__							)    ->    Dict[str, int]:

										'''simple docstring'''




										if self.framework != "pt":
																	raise ValueError("The ZeroShotObjectDetectionPipeline is only available in PyTorch."							)
										snake_case_ ,				snake_case_ ,				snake_case_ ,				snake_case_      =				box.int().tolist()
										snake_case_      =				{
										    "xmin": xmin,
										    "ymin": ymin,
										    "xmax": xmax,
										    "ymax": ymax,
										}
										return bbox






'''simple docstring'''





import gc
import random
import unittest

import torch

from diffusers import (
    IFImgaImgPipeline,
    IFImgaImgSuperResolutionPipeline,
    IFInpaintingPipeline,
    IFInpaintingSuperResolutionPipeline,
    IFPipeline,
    IFSuperResolutionPipeline,
)
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
from . import IFPipelineTesterMixin




@skip_mps
class 			_snake_case		(     lowercase_						,						lowercase_						,						unittest.TestCase							):
			lowerCAmelCase_					:				List[str]							=   IFPipeline
			lowerCAmelCase_					:				int							=   TEXT_TO_IMAGE_PARAMS - {"width", "height", "latents"}
			lowerCAmelCase_					:				Optional[int]							=   TEXT_TO_IMAGE_BATCH_PARAMS
			lowerCAmelCase_					:				List[Any]							=   PipelineTesterMixin.required_optional_params - {"latents"}




			def        lowerCAmelCase__    ( self							)    ->    Optional[Any]:

										'''simple docstring'''




										return self._get_dummy_components()




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__=0							)    ->    str:

										'''simple docstring'''




										if str(a__							).startswith("mps"							):
																	snake_case_      =				torch.manual_seed(a__							)
										else:
																	snake_case_      =				torch.Generator(device=a__							).manual_seed(a__							)

										snake_case_      =				{
										    "prompt": "A painting of a squirrel eating a burger",
										    "generator": generator,
										    "num_inference_steps": 2,
										    "output_type": "numpy",
										}

										return inputs




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

										'''simple docstring'''




										self._test_save_load_optional_components()




			@unittest.skipIf(torch_device != "cuda"    ,							reason="float16 requires CUDA"							)
			def        lowerCAmelCase__    ( self							)    ->    str:

										'''simple docstring'''




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




			def        lowerCAmelCase__    ( self							)    ->    List[Any]:

										'''simple docstring'''




										self._test_attention_slicing_forward_pass(expected_max_diff=1e-2							)




			def        lowerCAmelCase__    ( self							)    ->    int:

										'''simple docstring'''




										self._test_save_load_local()




			def        lowerCAmelCase__    ( self							)    ->    int:

										'''simple docstring'''




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




			@unittest.skipIf(
			    torch_device != "cuda" or not is_xformers_available()    ,							reason="XFormers attention is only available with CUDA and `xformers` installed"    ,							)
			def        lowerCAmelCase__    ( self							)    ->    List[str]:

										'''simple docstring'''




										self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3							)




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




			def        lowerCAmelCase__    ( self							)    ->    Union[str, Any]:

										'''simple docstring'''




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




			def        lowerCAmelCase__    ( self							)    ->    Union[str, Any]:

										'''simple docstring'''




										snake_case_      =				IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0"    ,							variant="fp16"    ,							torch_dtype=torch.floataa							)

										snake_case_      =				IFSuperResolutionPipeline.from_pretrained(
										    "DeepFloyd/IF-II-L-v1.0"    ,							variant="fp16"    ,							torch_dtype=torch.floataa    ,							text_encoder=a__    ,							tokenizer=a__							)

										# pre compute text embeddings and remove T5 to save memory

										pipe_a.text_encoder.to("cuda"							)

										snake_case_ ,				snake_case_      =				pipe_a.encode_prompt("anime turtle"    ,							device="cuda"							)

										del pipe_a.tokenizer
										del pipe_a.text_encoder
										gc.collect()

										snake_case_      =				None
										snake_case_      =				None

										pipe_a.enable_model_cpu_offload()
										pipe_a.enable_model_cpu_offload()

										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)
										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)

										self._test_if(a__    ,							a__    ,							a__    ,							a__							)

										pipe_a.remove_all_hooks()
										pipe_a.remove_all_hooks()

										# img2img

										snake_case_      =				IFImgaImgPipeline(**pipe_a.components							)
										snake_case_      =				IFImgaImgSuperResolutionPipeline(**pipe_a.components							)

										pipe_a.enable_model_cpu_offload()
										pipe_a.enable_model_cpu_offload()

										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)
										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)

										self._test_if_imgaimg(a__    ,							a__    ,							a__    ,							a__							)

										pipe_a.remove_all_hooks()
										pipe_a.remove_all_hooks()

										# inpainting

										snake_case_      =				IFInpaintingPipeline(**pipe_a.components							)
										snake_case_      =				IFInpaintingSuperResolutionPipeline(**pipe_a.components							)

										pipe_a.enable_model_cpu_offload()
										pipe_a.enable_model_cpu_offload()

										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)
										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)

										self._test_if_inpainting(a__    ,							a__    ,							a__    ,							a__							)




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__    ,							a__    ,							a__							)    ->    Dict:

										'''simple docstring'''




										_start_torch_memory_measurement()

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)
										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							num_inference_steps=2    ,							generator=a__    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

										assert image.shape == (64, 64, 3)

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 13 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)

										# pipeline 2

										_start_torch_memory_measurement()

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)

										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(0							)							).to(a__							)

										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							image=a__    ,							generator=a__    ,							num_inference_steps=2    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

										assert image.shape == (256, 256, 3)

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 4 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__    ,							a__    ,							a__							)    ->    Dict:

										'''simple docstring'''




										_start_torch_memory_measurement()

										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(0							)							).to(a__							)

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)

										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							image=a__    ,							num_inference_steps=2    ,							generator=a__    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

										assert image.shape == (64, 64, 3)

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 10 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)

										# pipeline 2

										_start_torch_memory_measurement()

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)

										snake_case_      =				floats_tensor((1, 3, 256, 256)    ,							rng=random.Random(0							)							).to(a__							)
										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(0							)							).to(a__							)

										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							image=a__    ,							original_image=a__    ,							generator=a__    ,							num_inference_steps=2    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

										assert image.shape == (256, 256, 3)

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 4 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__    ,							a__    ,							a__							)    ->    str:

										'''simple docstring'''




										_start_torch_memory_measurement()

										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(0							)							).to(a__							)
										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(1							)							).to(a__							)

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)
										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							image=a__    ,							mask_image=a__    ,							num_inference_steps=2    ,							generator=a__    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

										assert image.shape == (64, 64, 3)

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 10 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)

										# pipeline 2

										_start_torch_memory_measurement()

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)

										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(0							)							).to(a__							)
										snake_case_      =				floats_tensor((1, 3, 256, 256)    ,							rng=random.Random(0							)							).to(a__							)
										snake_case_      =				floats_tensor((1, 3, 256, 256)    ,							rng=random.Random(1							)							).to(a__							)

										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							image=a__    ,							mask_image=a__    ,							original_image=a__    ,							generator=a__    ,							num_inference_steps=2    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

										assert image.shape == (256, 256, 3)

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 4 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)


def 					UpperCamelCase_(     ):

							'''simple docstring'''






							torch.cuda.empty_cache()
							torch.cuda.reset_max_memory_allocated()
							torch.cuda.reset_peak_memory_stats()




