

'''simple docstring'''

import gc
import random
import tempfile
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMInverseScheduler,
    DDIMScheduler,
    DPMSolverMultistepInverseScheduler,
    DPMSolverMultistepScheduler,
    StableDiffusionDiffEditPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_image, slow
from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()







class   UpperCamelCase__    (   __SCREAMING_SNAKE_CASE							,							__SCREAMING_SNAKE_CASE							,							unittest.TestCase   ):


		"""simple docstring"""

		SCREAMING_SNAKE_CASE__  :	List[str]   =							StableDiffusionDiffEditPipeline
		SCREAMING_SNAKE_CASE__  :	int   =							TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"height", "width", "image"} | {"image_latents"}
		SCREAMING_SNAKE_CASE__  :	Union[str, Any]   =							TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {"image"} | {"image_latents"}
		SCREAMING_SNAKE_CASE__  :	Optional[int]   =							frozenset(
		    []   )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
		SCREAMING_SNAKE_CASE__  :	Optional[int]   =							frozenset([]   )







		def       A_       ( self			):


							'''simple docstring'''

							torch.manual_seed(0			)
							UpperCAmelCase		:							Union[str, Any]   					=   UNetaDConditionModel(
							    block_out_channels=(3_2, 6_4)    ,			layers_per_block=2    ,			sample_size=3_2    ,			in_channels=4    ,			out_channels=4    ,			down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")    ,			up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")    ,			cross_attention_dim=3_2    ,			attention_head_dim=(2, 4)    ,			use_linear_projection=UpperCAmelCase_    ,			)
							UpperCAmelCase		:							List[str]   					=   DDIMScheduler(
							    beta_start=0.0_0085    ,			beta_end=0.012    ,			beta_schedule="scaled_linear"    ,			clip_sample=UpperCAmelCase_    ,			set_alpha_to_one=UpperCAmelCase_    ,			)
							UpperCAmelCase		:							Optional[Any]   					=   DDIMInverseScheduler(
							    beta_start=0.0_0085    ,			beta_end=0.012    ,			beta_schedule="scaled_linear"    ,			clip_sample=UpperCAmelCase_    ,			set_alpha_to_zero=UpperCAmelCase_    ,			)
							torch.manual_seed(0			)
							UpperCAmelCase		:							Optional[int]   					=   AutoencoderKL(
							    block_out_channels=[3_2, 6_4]    ,			in_channels=3    ,			out_channels=3    ,			down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]    ,			up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]    ,			latent_channels=4    ,			sample_size=1_2_8    ,			)
							torch.manual_seed(0			)
							UpperCAmelCase		:							Dict   					=   CLIPTextConfig(
							    bos_token_id=0    ,			eos_token_id=2    ,			hidden_size=3_2    ,			intermediate_size=3_7    ,			layer_norm_eps=1e-05    ,			num_attention_heads=4    ,			num_hidden_layers=5    ,			pad_token_id=1    ,			vocab_size=1_0_0_0    ,			hidden_act="gelu"    ,			projection_dim=5_1_2    ,			)
							UpperCAmelCase		:							Dict   					=   CLIPTextModel(UpperCAmelCase_			)
							UpperCAmelCase		:							List[Any]   					=   CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"			)

							UpperCAmelCase		:							str   					=   {
							    "unet": unet,
							    "scheduler": scheduler,
							    "inverse_scheduler": inverse_scheduler,
							    "vae": vae,
							    "text_encoder": text_encoder,
							    "tokenizer": tokenizer,
							    "safety_checker": None,
							    "feature_extractor": None,
							}

							return components







		def       A_       ( self    ,			snake_case    ,			snake_case=0			):


							'''simple docstring'''

							UpperCAmelCase		:							Optional[Any]   					=   floats_tensor((1, 1_6, 1_6)    ,			rng=random.Random(UpperCAmelCase_			)			).to(UpperCAmelCase_			)
							UpperCAmelCase		:							Tuple   					=   floats_tensor((1, 2, 4, 1_6, 1_6)    ,			rng=random.Random(UpperCAmelCase_			)			).to(UpperCAmelCase_			)
							if str(UpperCAmelCase_			).startswith("mps"			):
												UpperCAmelCase		:							List[Any]   					=   torch.manual_seed(UpperCAmelCase_			)
							else:
												UpperCAmelCase		:							Optional[int]   					=   torch.Generator(device=UpperCAmelCase_			).manual_seed(UpperCAmelCase_			)
							UpperCAmelCase		:							List[Any]   					=   {
							    "prompt": "a dog and a newt",
							    "mask_image": mask,
							    "image_latents": latents,
							    "generator": generator,
							    "num_inference_steps": 2,
							    "inpaint_strength": 1.0,
							    "guidance_scale": 6.0,
							    "output_type": "numpy",
							}

							return inputs







		def       A_       ( self    ,			snake_case    ,			snake_case=0			):


							'''simple docstring'''

							UpperCAmelCase		:							List[str]   					=   floats_tensor((1, 3, 3_2, 3_2)    ,			rng=random.Random(UpperCAmelCase_			)			).to(UpperCAmelCase_			)
							UpperCAmelCase		:							Optional[Any]   					=   image.cpu().permute(0    ,			2    ,			3    ,			1			)[0]
							UpperCAmelCase		:							Optional[int]   					=   Image.fromarray(np.uinta(UpperCAmelCase_			)			).convert("RGB"			)
							if str(UpperCAmelCase_			).startswith("mps"			):
												UpperCAmelCase		:							Union[str, Any]   					=   torch.manual_seed(UpperCAmelCase_			)
							else:
												UpperCAmelCase		:							Union[str, Any]   					=   torch.Generator(device=UpperCAmelCase_			).manual_seed(UpperCAmelCase_			)
							UpperCAmelCase		:							List[str]   					=   {
							    "image": image,
							    "source_prompt": "a cat and a frog",
							    "target_prompt": "a dog and a newt",
							    "generator": generator,
							    "num_inference_steps": 2,
							    "num_maps_per_mask": 2,
							    "mask_encode_strength": 1.0,
							    "guidance_scale": 6.0,
							    "output_type": "numpy",
							}

							return inputs







		def       A_       ( self    ,			snake_case    ,			snake_case=0			):


							'''simple docstring'''

							UpperCAmelCase		:							Tuple   					=   floats_tensor((1, 3, 3_2, 3_2)    ,			rng=random.Random(UpperCAmelCase_			)			).to(UpperCAmelCase_			)
							UpperCAmelCase		:							str   					=   image.cpu().permute(0    ,			2    ,			3    ,			1			)[0]
							UpperCAmelCase		:							Any   					=   Image.fromarray(np.uinta(UpperCAmelCase_			)			).convert("RGB"			)
							if str(UpperCAmelCase_			).startswith("mps"			):
												UpperCAmelCase		:							Dict   					=   torch.manual_seed(UpperCAmelCase_			)
							else:
												UpperCAmelCase		:							int   					=   torch.Generator(device=UpperCAmelCase_			).manual_seed(UpperCAmelCase_			)
							UpperCAmelCase		:							Dict   					=   {
							    "image": image,
							    "prompt": "a cat and a frog",
							    "generator": generator,
							    "num_inference_steps": 2,
							    "inpaint_strength": 1.0,
							    "guidance_scale": 6.0,
							    "decode_latents": True,
							    "output_type": "numpy",
							}
							return inputs







		def       A_       ( self			):


							'''simple docstring'''

							if not hasattr(self.pipeline_class    ,			"_optional_components"			):
												return

							UpperCAmelCase		:							Dict   					=   self.get_dummy_components()
							UpperCAmelCase		:							Optional[Any]   					=   self.pipeline_class(**UpperCAmelCase_			)
							pipe.to(UpperCAmelCase_			)
							pipe.set_progress_bar_config(disable=UpperCAmelCase_			)

							# set all optional components to None and update pipeline config accordingly
							for optional_component in pipe._optional_components:
												setattr(UpperCAmelCase_    ,			UpperCAmelCase_    ,			UpperCAmelCase_			)
							pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components}			)

							UpperCAmelCase		:							Union[str, Any]   					=   self.get_dummy_inputs(UpperCAmelCase_			)
							UpperCAmelCase		:							Optional[Any]   					=   pipe(**UpperCAmelCase_			)[0]

							with tempfile.TemporaryDirectory() as tmpdir:
												pipe.save_pretrained(UpperCAmelCase_			)
												UpperCAmelCase		:							int   					=   self.pipeline_class.from_pretrained(UpperCAmelCase_			)
												pipe_loaded.to(UpperCAmelCase_			)
												pipe_loaded.set_progress_bar_config(disable=UpperCAmelCase_			)

							for optional_component in pipe._optional_components:
												self.assertTrue(
												    getattr(UpperCAmelCase_    ,			UpperCAmelCase_			) is None    ,			f"`{optional_component}` did not stay set to None after loading."    ,			)

							UpperCAmelCase		:							Optional[int]   					=   self.get_dummy_inputs(UpperCAmelCase_			)
							UpperCAmelCase		:							int   					=   pipe_loaded(**UpperCAmelCase_			)[0]

							UpperCAmelCase		:							int   					=   np.abs(output - output_loaded			).max()
							self.assertLess(UpperCAmelCase_    ,			1e-4			)







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase		:							List[str]   					=   "cpu"

							UpperCAmelCase		:							List[Any]   					=   self.get_dummy_components()
							UpperCAmelCase		:							int   					=   self.pipeline_class(**UpperCAmelCase_			)
							pipe.to(UpperCAmelCase_			)
							pipe.set_progress_bar_config(disable=UpperCAmelCase_			)

							UpperCAmelCase		:							Optional[int]   					=   self.get_dummy_mask_inputs(UpperCAmelCase_			)
							UpperCAmelCase		:							Dict   					=   pipe.generate_mask(**UpperCAmelCase_			)
							UpperCAmelCase		:							List[Any]   					=   mask[0, -3:, -3:]

							self.assertEqual(mask.shape    ,			(1, 1_6, 1_6)			)
							UpperCAmelCase		:							int   					=   np.array([0] * 9			)
							UpperCAmelCase		:							Tuple   					=   np.abs(mask_slice.flatten() - expected_slice			).max()
							self.assertLessEqual(UpperCAmelCase_    ,			1e-3			)
							self.assertEqual(mask[0, -3, -4]    ,			0			)







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase		:							str   					=   "cpu"

							UpperCAmelCase		:							Optional[Any]   					=   self.get_dummy_components()
							UpperCAmelCase		:							Optional[Any]   					=   self.pipeline_class(**UpperCAmelCase_			)
							pipe.to(UpperCAmelCase_			)
							pipe.set_progress_bar_config(disable=UpperCAmelCase_			)

							UpperCAmelCase		:							Tuple   					=   self.get_dummy_inversion_inputs(UpperCAmelCase_			)
							UpperCAmelCase		:							List[Any]   					=   pipe.invert(**UpperCAmelCase_			).images
							UpperCAmelCase		:							Union[str, Any]   					=   image[0, -1, -3:, -3:]

							self.assertEqual(image.shape    ,			(2, 3_2, 3_2, 3)			)
							UpperCAmelCase		:							int   					=   np.array(
							    [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.5_1050, 0.5015, 0.4407, 0.4799]    ,			)
							UpperCAmelCase		:							Optional[int]   					=   np.abs(image_slice.flatten() - expected_slice			).max()
							self.assertLessEqual(UpperCAmelCase_    ,			1e-3			)







		def       A_       ( self			):


							'''simple docstring'''

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







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase		:							Any   					=   "cpu"

							UpperCAmelCase		:							Any   					=   self.get_dummy_components()

							UpperCAmelCase		:							List[Any]   					=   {"beta_start": 0.0_0085, "beta_end": 0.012, "beta_schedule": "scaled_linear"}
							UpperCAmelCase		:							List[Any]   					=   DPMSolverMultistepScheduler(**UpperCAmelCase_			)
							UpperCAmelCase		:							Any   					=   DPMSolverMultistepInverseScheduler(**UpperCAmelCase_			)

							UpperCAmelCase		:							Union[str, Any]   					=   self.pipeline_class(**UpperCAmelCase_			)
							pipe.to(UpperCAmelCase_			)
							pipe.set_progress_bar_config(disable=UpperCAmelCase_			)

							UpperCAmelCase		:							Dict   					=   self.get_dummy_inversion_inputs(UpperCAmelCase_			)
							UpperCAmelCase		:							Union[str, Any]   					=   pipe.invert(**UpperCAmelCase_			).images
							UpperCAmelCase		:							List[Any]   					=   image[0, -1, -3:, -3:]

							self.assertEqual(image.shape    ,			(2, 3_2, 3_2, 3)			)
							UpperCAmelCase		:							Optional[int]   					=   np.array(
							    [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.5_1050, 0.5015, 0.4407, 0.4799]    ,			)
							UpperCAmelCase		:							int   					=   np.abs(image_slice.flatten() - expected_slice			).max()
							self.assertLessEqual(UpperCAmelCase_    ,			1e-3			)







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


		"""simple docstring"""

		def       A_       ( self			):


							'''simple docstring'''

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







		@classmethod
		def       A_       ( cls			):


							'''simple docstring'''

							UpperCAmelCase		:							Tuple   					=   load_image(
							    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png"			)

							UpperCAmelCase		:							Optional[int]   					=   raw_image.convert("RGB"			).resize((7_6_8, 7_6_8)			)

							UpperCAmelCase		:							Any   					=   raw_image







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase		:							Optional[Any]   					=   torch.manual_seed(0			)

							UpperCAmelCase		:							List[str]   					=   StableDiffusionDiffEditPipeline.from_pretrained(
							    "stabilityai/stable-diffusion-2-1"    ,			safety_checker=UpperCAmelCase_    ,			torch_dtype=torch.floataa			)
							UpperCAmelCase		:							int   					=   DDIMScheduler.from_config(pipe.scheduler.config			)
							UpperCAmelCase		:							int   					=   DDIMInverseScheduler.from_config(pipe.scheduler.config			)
							pipe.enable_model_cpu_offload()
							pipe.set_progress_bar_config(disable=UpperCAmelCase_			)

							UpperCAmelCase		:							Optional[Any]   					=   "a bowl of fruit"
							UpperCAmelCase		:							List[str]   					=   "a bowl of pears"

							UpperCAmelCase		:							Tuple   					=   pipe.generate_mask(
							    image=self.raw_image    ,			source_prompt=UpperCAmelCase_    ,			target_prompt=UpperCAmelCase_    ,			generator=UpperCAmelCase_    ,			)

							UpperCAmelCase		:							Optional[Any]   					=   pipe.invert(
							    prompt=UpperCAmelCase_    ,			image=self.raw_image    ,			inpaint_strength=0.7    ,			generator=UpperCAmelCase_			).latents

							UpperCAmelCase		:							Optional[int]   					=   pipe(
							    prompt=UpperCAmelCase_    ,			mask_image=UpperCAmelCase_    ,			image_latents=UpperCAmelCase_    ,			generator=UpperCAmelCase_    ,			negative_prompt=UpperCAmelCase_    ,			inpaint_strength=0.7    ,			output_type="numpy"    ,			).images[0]

							UpperCAmelCase		:							int   					=   (
							    np.array(
							        load_image(
							            "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
							            "/diffedit/pears.png"			).resize((7_6_8, 7_6_8)			)			)
							    / 2_5_5
							)
							assert np.abs((expected_image - image).max()			) < 5e-1







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase		:							str   					=   torch.manual_seed(0			)

							UpperCAmelCase		:							Optional[Any]   					=   StableDiffusionDiffEditPipeline.from_pretrained(
							    "stabilityai/stable-diffusion-2-1"    ,			safety_checker=UpperCAmelCase_    ,			torch_dtype=torch.floataa			)
							UpperCAmelCase		:							Dict   					=   DPMSolverMultistepScheduler.from_config(pipe.scheduler.config			)
							UpperCAmelCase		:							List[str]   					=   DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config			)
							pipe.enable_model_cpu_offload()
							pipe.set_progress_bar_config(disable=UpperCAmelCase_			)

							UpperCAmelCase		:							Dict   					=   "a bowl of fruit"
							UpperCAmelCase		:							Optional[Any]   					=   "a bowl of pears"

							UpperCAmelCase		:							int   					=   pipe.generate_mask(
							    image=self.raw_image    ,			source_prompt=UpperCAmelCase_    ,			target_prompt=UpperCAmelCase_    ,			generator=UpperCAmelCase_    ,			)

							UpperCAmelCase		:							List[str]   					=   pipe.invert(
							    prompt=UpperCAmelCase_    ,			image=self.raw_image    ,			inpaint_strength=0.7    ,			generator=UpperCAmelCase_    ,			num_inference_steps=2_5    ,			).latents

							UpperCAmelCase		:							List[Any]   					=   pipe(
							    prompt=UpperCAmelCase_    ,			mask_image=UpperCAmelCase_    ,			image_latents=UpperCAmelCase_    ,			generator=UpperCAmelCase_    ,			negative_prompt=UpperCAmelCase_    ,			inpaint_strength=0.7    ,			num_inference_steps=2_5    ,			output_type="numpy"    ,			).images[0]

							UpperCAmelCase		:							List[Any]   					=   (
							    np.array(
							        load_image(
							            "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
							            "/diffedit/pears.png"			).resize((7_6_8, 7_6_8)			)			)
							    / 2_5_5
							)
							assert np.abs((expected_image - image).max()			) < 5e-1







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

__A									=				logging.get_logger(__name__)



@add_end_docstrings(__SCREAMING_SNAKE_CASE    )
class    _SCREAMING_SNAKE_CASE						(	__SCREAMING_SNAKE_CASE    ):







 '''simple docstring'''

 def __init__(self				:   Tuple       , **UpperCAmelCase_				:   Tuple)       ->Any:



   '''simple docstring'''



   super().__init__(**UpperCAmelCase_)

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

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

 def __call__(self				:   Optional[int]       , UpperCAmelCase_				:   Union[str, "Image.Image", List[Dict[str, Any]]]       , UpperCAmelCase_				:   Union[str, List[str]] = None       , **UpperCAmelCase_				:   List[str]       , )       ->Union[str, Any]:



   '''simple docstring'''



   if "text_queries" in kwargs:
     lowerCamelCase__:      Any			  =kwargs.pop("text_queries")

   if isinstance(UpperCAmelCase_       , (str, Image.Image)):
     lowerCamelCase__:      List[Any]			  ={"image": image, "candidate_labels": candidate_labels}
   else:
     lowerCamelCase__:      Any			  =image
   lowerCamelCase__:      Dict			  =super().__call__(UpperCAmelCase_       , **UpperCAmelCase_)
   return results

 def 							SCREAMING_SNAKE_CASE_					(self				:   Optional[int]       , **UpperCAmelCase_				:   Union[str, Any])       ->Dict:



   '''simple docstring'''



   lowerCamelCase__:      List[str]			  ={}
   if "threshold" in kwargs:
     lowerCamelCase__:      List[Any]			  =kwargs["threshold"]
   if "top_k" in kwargs:
     lowerCamelCase__:      Any			  =kwargs["top_k"]
   return {}, {}, postprocess_params

 def 							SCREAMING_SNAKE_CASE_					(self				:   str       , UpperCAmelCase_				:   List[Any])       ->Union[str, Any]:



   '''simple docstring'''



   lowerCamelCase__:      List[Any]			  =load_image(inputs["image"])
   lowerCamelCase__:      Dict			  =inputs["candidate_labels"]
   if isinstance(UpperCAmelCase_       , UpperCAmelCase_):
     lowerCamelCase__:      Any			  =candidate_labels.split(",")

   lowerCamelCase__:      Optional[int]			  =torch.tensor([[image.height, image.width]]       , dtype=torch.intaa)
   for i, candidate_label in enumerate(UpperCAmelCase_):
     lowerCamelCase__:      Dict			  =self.tokenizer(UpperCAmelCase_       , return_tensors=self.framework)
     lowerCamelCase__:      Union[str, Any]			  =self.image_processor(UpperCAmelCase_       , return_tensors=self.framework)
     yield {
         "is_last": i == len(UpperCAmelCase_) - 1,
         "target_size": target_size,
         "candidate_label": candidate_label,
         **text_inputs,
         **image_features,
     }

 def 							SCREAMING_SNAKE_CASE_					(self				:   Optional[Any]       , UpperCAmelCase_				:   Tuple)       ->Optional[int]:



   '''simple docstring'''



   lowerCamelCase__:      Dict			  =model_inputs.pop("target_size")
   lowerCamelCase__:      Dict			  =model_inputs.pop("candidate_label")
   lowerCamelCase__:      Dict			  =model_inputs.pop("is_last")

   lowerCamelCase__:      Union[str, Any]			  =self.model(**UpperCAmelCase_)

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

 def 							SCREAMING_SNAKE_CASE_					(self				:   Optional[int]       , UpperCAmelCase_				:   int       , UpperCAmelCase_				:   Any=0.1       , UpperCAmelCase_				:   str=None)       ->Tuple:



   '''simple docstring'''



   lowerCamelCase__:      Union[str, Any]			  =[]
   for model_output in model_outputs:
     lowerCamelCase__:      Optional[Any]			  =model_output["candidate_label"]
     lowerCamelCase__:      Tuple			  =BaseModelOutput(UpperCAmelCase_)
     lowerCamelCase__:      Dict			  =self.image_processor.post_process_object_detection(
         outputs=UpperCAmelCase_       , threshold=UpperCAmelCase_       , target_sizes=model_output["target_size"])[0]

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

       lowerCamelCase__:      Optional[Any]			  ={"score": score, "label": label, "box": box}
       results.append(UpperCAmelCase_)

   lowerCamelCase__:      List[str]			  =sorted(UpperCAmelCase_       , key=lambda UpperCAmelCase_: x["score"]       , reverse=UpperCAmelCase_)
   if top_k:
     lowerCamelCase__:      Dict			  =results[:top_k]

   return results







 def 							SCREAMING_SNAKE_CASE_					(self				:   str       , UpperCAmelCase_				:   "torch.Tensor")       ->Dict[str, int]:



   '''simple docstring'''



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

