



"""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(lowercase_       )
class 					a	(  lowercase_       ):



  def __init__(						self :					Dict       ,		**lowerCAmelCase :					List[Any]		)     ->					int:


     '''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]       ,		lowerCAmelCase :					Union[str, "Image.Image", List[Dict[str, Any]]]       ,		lowerCAmelCase :					Union[str, List[str]] = None       ,		**lowerCAmelCase :					str       ,		)     ->					List[Any]:


     '''simple docstring'''




     if "text_queries" in kwargs:
        SCREAMING_SNAKE_CASE_: List[str]     			=kwargs.pop("""text_queries"""		)

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



  def 	lowerCamelCase__       (						self :					Tuple       ,		**lowerCAmelCase :					str		)     ->					Tuple:


     '''simple docstring'''




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



  def 	lowerCamelCase__       (						self :					int       ,		lowerCAmelCase :					int		)     ->					List[str]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: int     			=load_image(inputs["""image"""]		)
     SCREAMING_SNAKE_CASE_: int     			=inputs["""candidate_labels"""]
     if isinstance(UpperCamelCase__       ,		UpperCamelCase__		):
        SCREAMING_SNAKE_CASE_: List[Any]     			=candidate_labels.split(""","""		)

     SCREAMING_SNAKE_CASE_: Dict     			=torch.tensor([[image.height, image.width]]       ,		dtype=torch.intaa		)
     for i, candidate_label in enumerate(UpperCamelCase__		):
        SCREAMING_SNAKE_CASE_: Optional[Any]     			=self.tokenizer(UpperCamelCase__       ,		return_tensors=self.framework		)
        SCREAMING_SNAKE_CASE_: Optional[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 	lowerCamelCase__       (						self :					Tuple       ,		lowerCAmelCase :					Union[str, Any]		)     ->					Dict:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Tuple     			=model_inputs.pop("""target_size"""		)
     SCREAMING_SNAKE_CASE_: Optional[Any]     			=model_inputs.pop("""candidate_label"""		)
     SCREAMING_SNAKE_CASE_: List[Any]     			=model_inputs.pop("""is_last"""		)

     SCREAMING_SNAKE_CASE_: List[str]     			=self.model(**UpperCamelCase__		)

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



  def 	lowerCamelCase__       (						self :					str       ,		lowerCAmelCase :					Any       ,		lowerCAmelCase :					List[str]=0.1       ,		lowerCAmelCase :					Optional[Any]=None		)     ->					List[str]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Optional[Any]     			=[]
     for model_output in model_outputs:
        SCREAMING_SNAKE_CASE_: str     			=model_output["""candidate_label"""]
        SCREAMING_SNAKE_CASE_: Optional[Any]     			=BaseModelOutput(UpperCamelCase__		)
        SCREAMING_SNAKE_CASE_: Optional[int]     			=self.image_processor.post_process_object_detection(
            outputs=UpperCamelCase__       ,		threshold=UpperCamelCase__       ,		target_sizes=model_output["""target_size"""]		)[0]

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

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

     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=sorted(UpperCamelCase__       ,		key=lambda lowerCAmelCase		: x["score"]       ,		reverse=UpperCamelCase__		)
     if top_k:
        SCREAMING_SNAKE_CASE_: Dict     			=results[:top_k]

     return results





  def 	lowerCamelCase__       (						self :					Dict       ,		lowerCAmelCase :					"torch.Tensor"		)     ->					List[str]:


     '''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_: List[str]     			=box.int().tolist()
     SCREAMING_SNAKE_CASE_: Union[str, Any]     			={
         """xmin""": xmin,
         """ymin""": ymin,
         """xmax""": xmax,
         """ymax""": ymax,
     }
     return bbox








"""simple docstring"""
def      __magic_name__				(							lowercase							,			lowercase ):
   return int((input_a, input_a).count(0 ) == 0 )





def      __magic_name__				(							):
   assert and_gate(0							,			0 ) == 0
   assert and_gate(0							,			1 ) == 0
   assert and_gate(1							,			0 ) == 0
   assert and_gate(1							,			1 ) == 1


if __name__ == "__main__":
   test_and_gate()
   print(and_gate(1, 0))
   print(and_gate(0, 0))
   print(and_gate(0, 1))
   print(and_gate(1, 1))



