





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(__snake_case     )
class    A__  (			__snake_case     ):





      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:
        UpperCamelCase      :   str			      =  kwargs.pop("text_queries"  )

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





      def 			__UpperCamelCase(					self			,				**A_  ):
       '''simple docstring'''




       UpperCamelCase      :   Dict			      =  {}
       if "threshold" in kwargs:
        UpperCamelCase      :   List[str]			      =  kwargs["threshold"]
       if "top_k" in kwargs:
        UpperCamelCase      :   Optional[int]			      =  kwargs["top_k"]
       return {}, {}, postprocess_params





      def 			__UpperCamelCase(					self			,				A_  ):
       '''simple docstring'''




       UpperCamelCase      :   Any			      =  load_image(inputs["image"]  )
       UpperCamelCase      :   str			      =  inputs["candidate_labels"]
       if isinstance(A_			,				A_  ):
        UpperCamelCase      :   Tuple			      =  candidate_labels.split(","  )

       UpperCamelCase      :   Optional[int]			      =  torch.tensor([[image.height, image.width]]			,				dtype=torch.intaa  )
       for i, candidate_label in enumerate(A_  ):
        UpperCamelCase      :   Dict			      =  self.tokenizer(A_			,				return_tensors=self.framework  )
        UpperCamelCase      :   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'''




       UpperCamelCase      :   Any			      =  model_inputs.pop("target_size"  )
       UpperCamelCase      :   int			      =  model_inputs.pop("candidate_label"  )
       UpperCamelCase      :   Any			      =  model_inputs.pop("is_last"  )

       UpperCamelCase      :   Optional[Any]			      =  self.model(**A_  )

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




       UpperCamelCase      :   List[Any]			      =  []
       for model_output in model_outputs:
        UpperCamelCase      :   Optional[Any]			      =  model_output["candidate_label"]
        UpperCamelCase      :   Optional[Any]			      =  BaseModelOutput(A_  )
        UpperCamelCase      :   Tuple			      =  self.image_processor.post_process_object_detection(
            outputs=A_			,				threshold=A_			,				target_sizes=model_output["target_size"]  )[0]

        for index in outputs["scores"].nonzero():
         UpperCamelCase      :   List[str]			      =  outputs["scores"][index].item()
         UpperCamelCase      :   Tuple			      =  self._get_bounding_box(outputs["boxes"][index][0]  )

         UpperCamelCase      :   Union[str, Any]			      =  {"score": score, "label": label, "box": box}
         results.append(A_  )

       UpperCamelCase      :   int			      =  sorted(A_			,				key=lambda A_  : x["score"]			,				reverse=A_  )
       if top_k:
        UpperCamelCase      :   Union[str, Any]			      =  results[:top_k]

       return results





      def 			__UpperCamelCase(					self			,				A_  ):
       '''simple docstring'''




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







def 						A_							(	_lowerCAmelCase	)		->					bool:
 UpperCamelCase      :   List[Any]			      =  0
 for ch in input_str:
  UpperCamelCase      :   Optional[Any]			      =  ord(_lowerCAmelCase	)
  UpperCamelCase      :   Optional[Any]			      =  pow(2				,  _lowerCAmelCase	)

  # If we already turned on bit for current character's unicode
  if bitmap >> ch_unicode & 1 == 1:
   return False
  bitmap |= ch_bit_index_on
 return True


if __name__ == "__main__":
    import doctest

    doctest.testmod()
