





'''simple docstring'''


import unittest

from transformers import AutoTokenizer, FalconConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import (
     FalconForCausalLM,
     FalconForQuestionAnswering,
     FalconForSequenceClassification,
     FalconForTokenClassification,
     FalconModel,
 )
class 				a_       :





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





        """simple docstring"""




        lowercase_      :Dict         =			parent
        lowercase_      :Optional[Any]         =			batch_size
        lowercase_      :Union[str, Any]         =			seq_length
        lowercase_      :int         =			is_training
        lowercase_      :int         =			use_input_mask
        lowercase_      :Optional[int]         =			use_token_type_ids
        lowercase_      :List[Any]         =			use_labels
        lowercase_      :Tuple         =			vocab_size
        lowercase_      :str         =			hidden_size
        lowercase_      :Any         =			num_hidden_layers
        lowercase_      :Tuple         =			num_attention_heads
        lowercase_      :List[Any]         =			intermediate_size
        lowercase_      :Dict         =			hidden_act
        lowercase_      :Union[str, Any]         =			hidden_dropout_prob
        lowercase_      :int         =			attention_probs_dropout_prob
        lowercase_      :Union[str, Any]         =			max_position_embeddings
        lowercase_      :List[Any]         =			type_vocab_size
        lowercase_      :Optional[int]         =			type_sequence_label_size
        lowercase_      :Dict         =			initializer_range
        lowercase_      :Dict         =			num_labels
        lowercase_      :List[str]         =			num_choices
        lowercase_      :List[Any]         =			scope





     def 							lowercase__				(			self		: Optional[int]						):





        """simple docstring"""




        lowercase_      :int         =			ids_tensor([self.batch_size, self.seq_length]     ,				self.vocab_size						)

        lowercase_      :Optional[Any]         =			None
        if self.use_input_mask:
           lowercase_      :Union[str, Any]         =			random_attention_mask([self.batch_size, self.seq_length]						)

        lowercase_      :Dict         =			None

        lowercase_      :Union[str, Any]         =			None
        lowercase_      :Tuple         =			None
        lowercase_      :Dict         =			None
        if self.use_labels:
           lowercase_      :Optional[int]         =			ids_tensor([self.batch_size]     ,				self.type_sequence_label_size						)
           lowercase_      :Dict         =			ids_tensor([self.batch_size, self.seq_length]     ,				self.num_labels						)
           lowercase_      :str         =			ids_tensor([self.batch_size]     ,				self.num_choices						)

        lowercase_      :str         =			self.get_config()

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





     def 							lowercase__				(			self		: List[str]						):





        """simple docstring"""




        return FalconConfig(
            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     ,				pad_token_id=1     ,				new_decoder_architecture=lowercase     ,				)





     def 							lowercase__				(			self		: Optional[int]     ,				lowercase		: Any     ,				lowercase		: Any     ,				lowercase		: str     ,				lowercase		: Tuple     ,				lowercase		: Dict     ,				lowercase		: Any     ,				lowercase		: Dict						):





        """simple docstring"""




        lowercase_      :List[str]         =			FalconModel(config=lowercase						)
        model.to(lowercase						)
        model.eval()
        lowercase_      :Dict         =			model(lowercase     ,				attention_mask=lowercase						)
        lowercase_      :Dict         =			model(lowercase						)
        self.parent.assertEqual(result.last_hidden_state.shape     ,				(self.batch_size, self.seq_length, self.hidden_size)						)





     def 							lowercase__				(			self		: Dict     ,				lowercase		: Optional[Any]     ,				lowercase		: Tuple     ,				lowercase		: List[Any]     ,				lowercase		: Any     ,				lowercase		: Tuple     ,				lowercase		: int     ,				lowercase		: str     ,				lowercase		: int     ,				lowercase		: Optional[Any]     ,				):





        """simple docstring"""




        lowercase_      :Tuple         =			True
        lowercase_      :Any         =			FalconModel(lowercase						)
        model.to(lowercase						)
        model.eval()
        lowercase_      :int         =			model(
            lowercase     ,				attention_mask=lowercase     ,				encoder_hidden_states=lowercase     ,				encoder_attention_mask=lowercase     ,				)
        lowercase_      :Dict         =			model(
            lowercase     ,				attention_mask=lowercase     ,				encoder_hidden_states=lowercase     ,				)
        lowercase_      :Tuple         =			model(lowercase     ,				attention_mask=lowercase						)
        self.parent.assertEqual(result.last_hidden_state.shape     ,				(self.batch_size, self.seq_length, self.hidden_size)						)





     def 							lowercase__				(			self		: Tuple     ,				lowercase		: int     ,				lowercase		: Union[str, Any]     ,				lowercase		: List[Any]     ,				lowercase		: Optional[Any]     ,				lowercase		: Any     ,				lowercase		: Union[str, Any]     ,				lowercase		: int     ,				lowercase		: Optional[Any]     ,				lowercase		: str     ,				):





        """simple docstring"""




        lowercase_      :Optional[Any]         =			FalconForCausalLM(config=lowercase						)
        model.to(lowercase						)
        model.eval()
        lowercase_      :Optional[Any]         =			model(lowercase     ,				attention_mask=lowercase     ,				labels=lowercase						)
        self.parent.assertEqual(result.logits.shape     ,				(self.batch_size, self.seq_length, self.vocab_size)						)





     def 							lowercase__				(			self		: str     ,				lowercase		: Optional[int]     ,				lowercase		: Dict     ,				lowercase		: List[str]     ,				lowercase		: List[Any]     ,				lowercase		: List[str]     ,				lowercase		: Tuple     ,				lowercase		: List[str]     ,				lowercase		: List[str]     ,				lowercase		: Optional[int]     ,				):





        """simple docstring"""




        lowercase_      :Any         =			True
        lowercase_      :Optional[int]         =			True
        lowercase_      :int         =			FalconForCausalLM(config=lowercase						)
        model.to(lowercase						)
        model.eval()

        # first forward pass
        lowercase_      :Dict         =			model(
            lowercase     ,				attention_mask=lowercase     ,				encoder_hidden_states=lowercase     ,				encoder_attention_mask=lowercase     ,				use_cache=lowercase     ,				)
        lowercase_      :Any         =			outputs.past_key_values

        # create hypothetical multiple next token and extent to next_input_ids
        lowercase_      :Dict         =			ids_tensor((self.batch_size, 3)     ,				config.vocab_size						)
        lowercase_      :int         =			ids_tensor((self.batch_size, 3)     ,				vocab_size=2						)

        # append to next input_ids and
        lowercase_      :Any         =			torch.cat([input_ids, next_tokens]     ,				dim=-1						)
        lowercase_      :Optional[int]         =			torch.cat([input_mask, next_mask]     ,				dim=-1						)

        lowercase_      :int         =			model(
            lowercase     ,				attention_mask=lowercase     ,				encoder_hidden_states=lowercase     ,				encoder_attention_mask=lowercase     ,				output_hidden_states=lowercase     ,				)["hidden_states"][0]
        lowercase_      :List[str]         =			model(
            lowercase     ,				attention_mask=lowercase     ,				encoder_hidden_states=lowercase     ,				encoder_attention_mask=lowercase     ,				past_key_values=lowercase     ,				output_hidden_states=lowercase     ,				)["hidden_states"][0]

        # select random slice
        lowercase_      :List[str]         =			ids_tensor((1,)     ,				output_from_past.shape[-1]						).item()
        lowercase_      :List[str]         =			output_from_no_past[:, -3:, random_slice_idx].detach()
        lowercase_      :List[str]         =			output_from_past[:, :, random_slice_idx].detach()

        self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]						)

        # test that outputs are equal for slice
        self.parent.assertTrue(torch.allclose(lowercase     ,				lowercase     ,				atol=1e-3						)						)







     def 							lowercase__				(			self		: int						):





        """simple docstring"""




        lowercase_      :Dict         =			self.prepare_config_and_inputs()
        (
            (
            lowercase_
        )      ,							(
            lowercase_
        )      ,							(
            lowercase_
        )      ,							(
            lowercase_
        )      ,							(
            lowercase_
        )      ,							(
            lowercase_
        )      ,							(
            lowercase_
        )      ,							
        )      :Union[str, Any]         =			config_and_inputs
        lowercase_      :int         =			{"input_ids": input_ids, "attention_mask": input_mask}
        return config, inputs_dict







@require_torch
class 				a_       (    _lowerCAmelCase     ,						_lowerCAmelCase     ,						_lowerCAmelCase     ,						unittest.TestCase							):
     __A								=      (
         (
             FalconModel,
             FalconForCausalLM,
             FalconForSequenceClassification,
             FalconForTokenClassification,
             FalconForQuestionAnswering,
         )
         if is_torch_available()
         else ()
     )
     __A								=      (FalconForCausalLM,) if is_torch_available() else ()
     __A								=      (
         {
             "feature-extraction": FalconModel,
             "text-classification": FalconForSequenceClassification,
             "text-generation": FalconForCausalLM,
             "question-answering": FalconForQuestionAnswering,
             "token-classification": FalconForTokenClassification,
             "zero-shot": FalconForSequenceClassification,
         }
         if is_torch_available()
         else {}
     )
     __A								=      False
     __A								=      False





     def 							lowercase__				(			self		: str						):





        """simple docstring"""




        lowercase_      :Any         =			FalconModelTester(self						)
        lowercase_      :int         =			ConfigTester(self     ,				config_class=lowercase     ,				hidden_size=37						)





     def 							lowercase__				(			self		: int						):





        """simple docstring"""




        self.config_tester.run_common_tests()





     def 							lowercase__				(			self		: str						):





        """simple docstring"""




        lowercase_      :List[str]         =			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowercase						)





     def 							lowercase__				(			self		: Any						):





        """simple docstring"""




        lowercase_      ,							*lowercase_      :List[str]         =			self.model_tester.prepare_config_and_inputs()
        for alibi in [True, False]:
           lowercase_      :Optional[int]         =			alibi
           self.model_tester.create_and_check_model(lowercase     ,				*lowercase						)





     def 							lowercase__				(			self		: Tuple						):





        """simple docstring"""




        lowercase_      ,							lowercase_      :Dict         =			self.model_tester.prepare_config_and_inputs_for_common()
        lowercase_      :int         =			3
        lowercase_      :int         =			input_dict["input_ids"]
        lowercase_      :Tuple         =			input_ids.ne(1						).to(lowercase						)
        lowercase_      :str         =			ids_tensor([self.model_tester.batch_size]     ,				self.model_tester.type_sequence_label_size						)
        lowercase_      :Any         =			FalconForSequenceClassification(lowercase						)
        model.to(lowercase						)
        model.eval()
        lowercase_      :Union[str, Any]         =			model(lowercase     ,				attention_mask=lowercase     ,				labels=lowercase						)
        self.assertEqual(result.logits.shape     ,				(self.model_tester.batch_size, self.model_tester.num_labels)						)





     def 							lowercase__				(			self		: str						):





        """simple docstring"""




        lowercase_      ,							lowercase_      :Tuple         =			self.model_tester.prepare_config_and_inputs_for_common()
        lowercase_      :Tuple         =			3
        lowercase_      :str         =			"single_label_classification"
        lowercase_      :int         =			input_dict["input_ids"]
        lowercase_      :int         =			input_ids.ne(1						).to(lowercase						)
        lowercase_      :Union[str, Any]         =			ids_tensor([self.model_tester.batch_size]     ,				self.model_tester.type_sequence_label_size						)
        lowercase_      :Tuple         =			FalconForSequenceClassification(lowercase						)
        model.to(lowercase						)
        model.eval()
        lowercase_      :List[str]         =			model(lowercase     ,				attention_mask=lowercase     ,				labels=lowercase						)
        self.assertEqual(result.logits.shape     ,				(self.model_tester.batch_size, self.model_tester.num_labels)						)





     def 							lowercase__				(			self		: Tuple						):





        """simple docstring"""




        lowercase_      ,							lowercase_      :List[str]         =			self.model_tester.prepare_config_and_inputs_for_common()
        lowercase_      :Dict         =			input_dict["input_ids"]
        lowercase_      :Optional[int]         =			FalconForCausalLM(lowercase						)
        model.to(lowercase						)
        model.eval()
        lowercase_      :int         =			model(lowercase     ,				use_cache=lowercase						)
        lowercase_      :Optional[int]         =			input_ids.shape[0]
        lowercase_      :Any         =			model._convert_to_rw_cache(result.past_key_values						)
        lowercase_      :Optional[int]         =			model._convert_cache_to_standard_format(lowercase     ,				lowercase						)
        for layer in range(len(lowercase						)						):
           for tensor_idx in range(2						):
              self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3						)
              self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4						)
              self.assertTrue(
                  torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx]						)						)





     def 							lowercase__				(			self		: Tuple						):





        """simple docstring"""




        lowercase_      ,							lowercase_      :List[str]         =			self.model_tester.prepare_config_and_inputs_for_common()
        lowercase_      :List[str]         =			3
        lowercase_      :int         =			"multi_label_classification"
        lowercase_      :List[Any]         =			input_dict["input_ids"]
        lowercase_      :Any         =			input_ids.ne(1						).to(lowercase						)
        lowercase_      :Any         =			ids_tensor(
            [self.model_tester.batch_size, config.num_labels]     ,				self.model_tester.type_sequence_label_size						).to(torch.float						)
        lowercase_      :int         =			FalconForSequenceClassification(lowercase						)
        model.to(lowercase						)
        model.eval()
        lowercase_      :str         =			model(lowercase     ,				attention_mask=lowercase     ,				labels=lowercase						)
        self.assertEqual(result.logits.shape     ,				(self.model_tester.batch_size, self.model_tester.num_labels)						)







     def 							lowercase__				(			self		: int						):





        """simple docstring"""




        for model_class in self.all_generative_model_classes:
           lowercase_      ,							lowercase_      :Optional[int]         =			self.model_tester.prepare_config_and_inputs_for_common()

           # If it doesn't support cache, pass the test
           if not hasattr(lowercase     ,				"use_cache"						):
              return

           lowercase_      :Dict         =			model_class(lowercase						).to(lowercase						)
           if "use_cache" not in inputs:
              lowercase_      :List[str]         =			True
           lowercase_      :List[str]         =			model(**lowercase						)

           # If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format)
           if "past_key_values" not in outputs:
              return

           lowercase_      :Dict         =			(
               getattr(lowercase     ,				"decoder_layers"     ,				lowercase						)
               or getattr(lowercase     ,				"num_decoder_layers"     ,				lowercase						)
               or config.num_hidden_layers
           )
           lowercase_      :List[Any]         =			getattr(lowercase     ,				"num_kv_heads"     ,				config.num_attention_heads						)
           lowercase_      :int         =			getattr(lowercase     ,				"d_model"     ,				config.hidden_size						)
           lowercase_      :List[str]         =			embed_dim // num_attention_heads

           lowercase_      :Tuple         =			outputs["past_key_values"]
           self.assertEqual(len(lowercase						)     ,				lowercase						)

           lowercase_      ,							lowercase_      :Any         =			inputs["input_ids"].shape
           for i in range(lowercase						):
              if config.new_decoder_architecture:
                 lowercase_      :Any         =			config.num_attention_heads
              elif config.multi_query:
                 lowercase_      :List[Any]         =			1
              self.assertEqual(len(past_kv[0]						)     ,				2						)  # K V for the decoder = 2
              self.assertEqual(
                  past_kv[i][0].shape     ,				(batch_size, num_attention_heads, seq_length, per_head_embed_dim)						)
              self.assertEqual(
                  past_kv[i][1].shape     ,				(batch_size, num_attention_heads, seq_length, per_head_embed_dim)						)







@require_torch
class 				a_       (    unittest.TestCase							):





     @slow
     def 							lowercase__				(			self		: int						):





        """simple docstring"""




        lowercase_      :List[Any]         =			AutoTokenizer.from_pretrained("Rocketknight1/falcon-rw-1b"						)
        lowercase_      :Dict         =			FalconForCausalLM.from_pretrained("Rocketknight1/falcon-rw-1b"						)
        model.eval()
        model.to(lowercase						)
        lowercase_      :Union[str, Any]         =			tokenizer("My favorite food is"     ,				return_tensors="pt"						).to(lowercase						)

        lowercase_      :List[str]         =			(
            "My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday."
        )

        lowercase_      :Optional[Any]         =			model.generate(**lowercase     ,				do_sample=lowercase     ,				max_new_tokens=19						)
        lowercase_      :str         =			tokenizer.batch_decode(lowercase						)[0]

        self.assertEqual(lowercase     ,				lowercase						)





     @slow
     def 							lowercase__				(			self		: str						):





        """simple docstring"""




        for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]:
           lowercase_      :Any         =			AutoTokenizer.from_pretrained(lowercase						)
           lowercase_      :Tuple         =			FalconForCausalLM.from_pretrained(lowercase						)
           model.eval()
           model.to(lowercase						)
           lowercase_      :Optional[int]         =			tokenizer("My favorite food is"     ,				return_tensors="pt"						).to(lowercase						)

           # We just test that these run without errors - the models are randomly initialized
           # and so the actual text outputs will be garbage
           model.generate(**lowercase     ,				do_sample=lowercase     ,				max_new_tokens=4						)
           model.generate(**lowercase     ,				do_sample=lowercase     ,				max_new_tokens=4						)
           model.generate(**lowercase     ,				num_beams=2     ,				max_new_tokens=4						)







     @slow
     def 							lowercase__				(			self		: str						):





        """simple docstring"""




        with torch.no_grad():
           for repo in [
               "Rocketknight1/falcon-rw-1b",
               "Rocketknight1/tiny-random-falcon-7b",
               "Rocketknight1/tiny-random-falcon-40b",
           ]:
              lowercase_      :List[Any]         =			AutoTokenizer.from_pretrained(lowercase						)
              lowercase_      :Any         =			FalconForCausalLM.from_pretrained(lowercase						)
              model.eval()
              model.to(device=lowercase						)
              lowercase_      :Optional[Any]         =			tokenizer("My favorite food is"     ,				return_tensors="pt"						).to(lowercase						)

              # Test results are the same with and without cache
              lowercase_      :List[str]         =			model.generate(**lowercase     ,				do_sample=lowercase     ,				max_new_tokens=20     ,				use_cache=lowercase						)
              lowercase_      :Tuple         =			model.generate(**lowercase     ,				do_sample=lowercase     ,				max_new_tokens=20     ,				use_cache=lowercase						)
              self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0						)









'''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

lowerCAmelCase :					Union[str, Any] 							=logging.get_logger(__name__)
@add_end_docstrings(_lowerCAmelCase							)
class 				a_       (    _lowerCAmelCase							):





     def __init__(			self		: List[Any]     ,				**lowercase		: Optional[int]						):





        """simple docstring"""




        super().__init__(**lowercase						)

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

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





     def __call__(			self		: Tuple     ,				lowercase		: Union[str, "Image.Image", List[Dict[str, Any]]]     ,				lowercase		: Union[str, List[str]] = None     ,				**lowercase		: str     ,				):





        """simple docstring"""




        if "text_queries" in kwargs:
           lowercase_      :List[Any]         =			kwargs.pop("text_queries"						)

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





     def 							lowercase__				(			self		: Optional[int]     ,				**lowercase		: List[str]						):





        """simple docstring"""




        lowercase_      :Tuple         =			{}
        if "threshold" in kwargs:
           lowercase_      :Dict         =			kwargs["threshold"]
        if "top_k" in kwargs:
           lowercase_      :Optional[Any]         =			kwargs["top_k"]
        return {}, {}, postprocess_params





     def 							lowercase__				(			self		: List[Any]     ,				lowercase		: Dict						):





        """simple docstring"""




        lowercase_      :Any         =			load_image(inputs["image"]						)
        lowercase_      :List[str]         =			inputs["candidate_labels"]
        if isinstance(lowercase     ,				lowercase						):
           lowercase_      :Union[str, Any]         =			candidate_labels.split(","						)

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





     def 							lowercase__				(			self		: List[str]     ,				lowercase		: List[str]						):





        """simple docstring"""




        lowercase_      :Dict         =			model_inputs.pop("target_size"						)
        lowercase_      :str         =			model_inputs.pop("candidate_label"						)
        lowercase_      :List[Any]         =			model_inputs.pop("is_last"						)

        lowercase_      :Optional[Any]         =			self.model(**lowercase						)

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





     def 							lowercase__				(			self		: Optional[int]     ,				lowercase		: List[str]     ,				lowercase		: List[str]=0.1     ,				lowercase		: Optional[int]=None						):





        """simple docstring"""




        lowercase_      :Dict         =			[]
        for model_output in model_outputs:
           lowercase_      :int         =			model_output["candidate_label"]
           lowercase_      :str         =			BaseModelOutput(lowercase						)
           lowercase_      :List[Any]         =			self.image_processor.post_process_object_detection(
               outputs=lowercase     ,				threshold=lowercase     ,				target_sizes=model_output["target_size"]						)[0]

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

              lowercase_      :int         =			{"score": score, "label": label, "box": box}
              results.append(lowercase						)

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

        return results







     def 							lowercase__				(			self		: Union[str, Any]     ,				lowercase		: "torch.Tensor"						):





        """simple docstring"""




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


