






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       __UpperCAmelCase		(_UpperCAmelCase    ):







			def __init__(	self:  Optional[Any]      ,	**UpperCAmelCase_:  Tuple     ):







									'''simple docstring'''




									super().__init__(**__lowerCAmelCase     )

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

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







			def __call__(	self:  Tuple      ,	UpperCAmelCase_:  str      ,	UpperCAmelCase_:  Union[str, Any] = None      ,	**UpperCAmelCase_:  List[Any]      ,	):







									'''simple docstring'''




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

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







			def 							UpperCamelCase      (	self:  str      ,	**UpperCAmelCase_:  Dict     ):







									'''simple docstring'''




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







			def 							UpperCamelCase      (	self:  Dict      ,	UpperCAmelCase_:  Optional[int]     ):







									'''simple docstring'''




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

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







			def 							UpperCamelCase      (	self:  List[Any]      ,	UpperCAmelCase_:  str     ):







									'''simple docstring'''




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

									_SCREAMING_SNAKE_CASE	      =  self.model(**__lowerCAmelCase     )

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







			def 							UpperCamelCase      (	self:  int      ,	UpperCAmelCase_:  Dict      ,	UpperCAmelCase_:  int=0.1      ,	UpperCAmelCase_:  Optional[Any]=None     ):







									'''simple docstring'''




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

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

																					_SCREAMING_SNAKE_CASE	      =  {"""score""": score, """label""": label, """box""": box}
																					results.append(__lowerCAmelCase     )

									_SCREAMING_SNAKE_CASE	      =  sorted(__lowerCAmelCase      ,	key=lambda UpperCAmelCase_     : x["score"]      ,	reverse=__lowerCAmelCase     )
									if top_k:
															_SCREAMING_SNAKE_CASE	      =  results[:top_k]

									return results







			def 							UpperCamelCase      (	self:  Tuple      ,	UpperCAmelCase_:  Any     ):







									'''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	      =  box.int().tolist()
									_SCREAMING_SNAKE_CASE	      =  {
									    """xmin""": xmin,
									    """ymin""": ymin,
									    """xmax""": xmax,
									    """ymax""": ymax,
									}
									return bbox


"""simple docstring"""






from ..utils import DummyObject, requires_backends





class  _A						(       metaclass=lowerCAmelCase	):
      snake_case__			:   str							  =	['torch', 'transformers', 'onnx']

      def __init__(						self		,       *__lowerCAmelCase		,       **__lowerCAmelCase						):







            """simple docstring"""



            requires_backends(self		,       ["""torch""", """transformers""", """onnx"""]						)

      @classmethod
      def 				A__       (						cls		,       *__lowerCAmelCase		,       **__lowerCAmelCase						):







            """simple docstring"""



            requires_backends(cls		,       ["""torch""", """transformers""", """onnx"""]						)







      @classmethod
      def 				A__       (						cls		,       *__lowerCAmelCase		,       **__lowerCAmelCase						):







            """simple docstring"""



            requires_backends(cls		,       ["""torch""", """transformers""", """onnx"""]						)






class  _A						(       metaclass=lowerCAmelCase	):
      snake_case__			:   List[Any]							  =	['torch', 'transformers', 'onnx']

      def __init__(						self		,       *__lowerCAmelCase		,       **__lowerCAmelCase						):







            """simple docstring"""



            requires_backends(self		,       ["""torch""", """transformers""", """onnx"""]						)

      @classmethod
      def 				A__       (						cls		,       *__lowerCAmelCase		,       **__lowerCAmelCase						):







            """simple docstring"""



            requires_backends(cls		,       ["""torch""", """transformers""", """onnx"""]						)







      @classmethod
      def 				A__       (						cls		,       *__lowerCAmelCase		,       **__lowerCAmelCase						):







            """simple docstring"""



            requires_backends(cls		,       ["""torch""", """transformers""", """onnx"""]						)






class  _A						(       metaclass=lowerCAmelCase	):
      snake_case__			:   Optional[Any]							  =	['torch', 'transformers', 'onnx']

      def __init__(						self		,       *__lowerCAmelCase		,       **__lowerCAmelCase						):







            """simple docstring"""



            requires_backends(self		,       ["""torch""", """transformers""", """onnx"""]						)

      @classmethod
      def 				A__       (						cls		,       *__lowerCAmelCase		,       **__lowerCAmelCase						):







            """simple docstring"""



            requires_backends(cls		,       ["""torch""", """transformers""", """onnx"""]						)







      @classmethod
      def 				A__       (						cls		,       *__lowerCAmelCase		,       **__lowerCAmelCase						):







            """simple docstring"""



            requires_backends(cls		,       ["""torch""", """transformers""", """onnx"""]						)






class  _A						(       metaclass=lowerCAmelCase	):
      snake_case__			:   int							  =	['torch', 'transformers', 'onnx']

      def __init__(						self		,       *__lowerCAmelCase		,       **__lowerCAmelCase						):







            """simple docstring"""



            requires_backends(self		,       ["""torch""", """transformers""", """onnx"""]						)

      @classmethod
      def 				A__       (						cls		,       *__lowerCAmelCase		,       **__lowerCAmelCase						):







            """simple docstring"""



            requires_backends(cls		,       ["""torch""", """transformers""", """onnx"""]						)







      @classmethod
      def 				A__       (						cls		,       *__lowerCAmelCase		,       **__lowerCAmelCase						):







            """simple docstring"""



            requires_backends(cls		,       ["""torch""", """transformers""", """onnx"""]						)






class  _A						(       metaclass=lowerCAmelCase	):
      snake_case__			:   List[str]							  =	['torch', 'transformers', 'onnx']

      def __init__(						self		,       *__lowerCAmelCase		,       **__lowerCAmelCase						):







            """simple docstring"""



            requires_backends(self		,       ["""torch""", """transformers""", """onnx"""]						)

      @classmethod
      def 				A__       (						cls		,       *__lowerCAmelCase		,       **__lowerCAmelCase						):







            """simple docstring"""



            requires_backends(cls		,       ["""torch""", """transformers""", """onnx"""]						)







      @classmethod
      def 				A__       (						cls		,       *__lowerCAmelCase		,       **__lowerCAmelCase						):







            """simple docstring"""



            requires_backends(cls		,       ["""torch""", """transformers""", """onnx"""]						)






class  _A						(       metaclass=lowerCAmelCase	):
      snake_case__			:   Optional[Any]							  =	['torch', 'transformers', 'onnx']

      def __init__(						self		,       *__lowerCAmelCase		,       **__lowerCAmelCase						):







            """simple docstring"""



            requires_backends(self		,       ["""torch""", """transformers""", """onnx"""]						)

      @classmethod
      def 				A__       (						cls		,       *__lowerCAmelCase		,       **__lowerCAmelCase						):







            """simple docstring"""



            requires_backends(cls		,       ["""torch""", """transformers""", """onnx"""]						)







      @classmethod
      def 				A__       (						cls		,       *__lowerCAmelCase		,       **__lowerCAmelCase						):







            """simple docstring"""



            requires_backends(cls		,       ["""torch""", """transformers""", """onnx"""]						)



