




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

UpperCamelCase_       =							logging.get_logger(__name__)






@add_end_docstrings(_UpperCAmelCase      )
class 				_a							(       _UpperCAmelCase      ):





       '''simple docstring'''






       def __init__(	self,				**A   ):







             '''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,				):







             '''simple docstring'''







             if "text_queries" in kwargs:
                   SCREAMING_SNAKE_CASE					:	Optional[Any]   =		kwargs.pop('text_queries'   )

             if isinstance(A,				(str, Image.Image)   ):
                   SCREAMING_SNAKE_CASE					:	List[Any]   =		{'image': image, 'candidate_labels': candidate_labels}
             else:
                   SCREAMING_SNAKE_CASE					:	Optional[Any]   =		image
             SCREAMING_SNAKE_CASE					:	Optional[int]   =		super().__call__(A,				**A   )
             return results







       def     UpperCamelCase_				(	self,				**A   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	int   =		{}
             if "threshold" in kwargs:
                   SCREAMING_SNAKE_CASE					:	Dict   =		kwargs['threshold']
             if "top_k" in kwargs:
                   SCREAMING_SNAKE_CASE					:	int   =		kwargs['top_k']
             return {}, {}, postprocess_params







       def     UpperCamelCase_				(	self,				A   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	Optional[Any]   =		load_image(inputs['image']   )
             SCREAMING_SNAKE_CASE					:	str   =		inputs['candidate_labels']
             if isinstance(A,				A   ):
                   SCREAMING_SNAKE_CASE					:	Dict   =		candidate_labels.split(','   )

             SCREAMING_SNAKE_CASE					:	Any   =		torch.tensor([[image.height, image.width]],				dtype=torch.intaa   )
             for i, candidate_label in enumerate(A   ):
                   SCREAMING_SNAKE_CASE					:	Any   =		self.tokenizer(A,				return_tensors=self.framework   )
                   SCREAMING_SNAKE_CASE					:	List[Any]   =		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     UpperCamelCase_				(	self,				A   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	Tuple   =		model_inputs.pop('target_size'   )
             SCREAMING_SNAKE_CASE					:	List[str]   =		model_inputs.pop('candidate_label'   )
             SCREAMING_SNAKE_CASE					:	Tuple   =		model_inputs.pop('is_last'   )

             SCREAMING_SNAKE_CASE					:	List[Any]   =		self.model(**A   )

             SCREAMING_SNAKE_CASE					:	Dict   =		{'target_size': target_size, 'candidate_label': candidate_label, 'is_last': is_last, **outputs}
             return model_outputs







       def     UpperCamelCase_				(	self,				A,				A=0.1,				A=None   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	Optional[int]   =		[]
             for model_output in model_outputs:
                   SCREAMING_SNAKE_CASE					:	Union[str, Any]   =		model_output['candidate_label']
                   SCREAMING_SNAKE_CASE					:	Optional[Any]   =		BaseModelOutput(A   )
                   SCREAMING_SNAKE_CASE					:	Optional[int]   =		self.image_processor.post_process_object_detection(
                       outputs=A,				threshold=A,				target_sizes=model_output['target_size']   )[0]

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

                         SCREAMING_SNAKE_CASE					:	str   =		{'score': score, 'label': label, 'box': box}
                         results.append(A   )

             SCREAMING_SNAKE_CASE					:	str   =		sorted(A,				key=lambda A   : x["score"],				reverse=A   )
             if top_k:
                   SCREAMING_SNAKE_CASE					:	Tuple   =		results[:top_k]

             return results







       def     UpperCamelCase_				(	self,				A   ):







             '''simple docstring'''







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









"""simple docstring"""





# This is the module that test_patching.py uses to test patch_submodule()

import os  # noqa: this is just for tests
import os as renamed_os  # noqa: this is just for tests
from os import path  # noqa: this is just for tests
from os import path as renamed_path  # noqa: this is just for tests
from os.path import join  # noqa: this is just for tests
from os.path import join as renamed_join  # noqa: this is just for tests


SCREAMING_SNAKE_CASE__					=   open  # noqa: we just need to have a builtin inside this module to test it properly






