



"""simple docstring"""
import re
import subprocess
import sys


UpperCAmelCase						:		Any			= subprocess.check_output("git merge-base main HEAD".split()).decode("utf-8")
UpperCAmelCase						:		Union[str, Any]			= (
    subprocess.check_output(F"git diff --diff-filter=d --name-only {fork_point_sha}".split()).decode("utf-8").split()
)

UpperCAmelCase						:		int			= "|".join(sys.argv[1:])
UpperCAmelCase						:		Optional[int]			= re.compile(rF"^({joined_dirs}).*?\.py$")

UpperCAmelCase						:		Any			= [x for x in modified_files if regex.match(x)]
print(" ".join(relevant_modified_files), end="")






"""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						:		Optional[Any]			= logging.get_logger(__name__)


@add_end_docstrings(__UpperCAmelCase   )
class    SCREAMING_SNAKE_CASE__ (							__UpperCAmelCase   ):

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







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







      """simple docstring"""







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

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

    def 					_UpperCAmelCase	(				self			:				Optional[Any] ,  **lowerCAmelCase_			:				Optional[Any]):







      """simple docstring"""







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

    def 					_UpperCAmelCase	(				self			:				int ,  lowerCAmelCase_			:				List[Any]):







      """simple docstring"""







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

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







      """simple docstring"""







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

      lowercase_								= self.model(**lowerCAmelCase_)

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

    def 					_UpperCAmelCase	(				self			:				int ,  lowerCAmelCase_			:				Optional[int] ,  lowerCAmelCase_			:				Tuple=0.1 ,  lowerCAmelCase_			:				List[str]=None):







      """simple docstring"""







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

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

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

      lowercase_								= sorted(lowerCAmelCase_ ,  key=lambda lowerCAmelCase_: x["score"] ,  reverse=lowerCAmelCase_)
      if top_k:
        lowercase_								= results[:top_k]

      return results




    def 					_UpperCAmelCase	(				self			:				Union[str, Any] ,  lowerCAmelCase_			:				"torch.Tensor"):







      """simple docstring"""







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

