






"""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(snake_case			)
class  lowerCamelCase__ (	snake_case			):






    def __init__(			self     ,**A ):
          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     ,):
          if "text_queries" in kwargs:
                UpperCAmelCase          =	kwargs.pop("""text_queries""" )

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






    def     _UpperCamelCase							(			self     ,**A ):
          UpperCAmelCase          =	{}
          if "threshold" in kwargs:
                UpperCAmelCase          =	kwargs["""threshold"""]
          if "top_k" in kwargs:
                UpperCAmelCase          =	kwargs["""top_k"""]
          return {}, {}, postprocess_params






    def     _UpperCamelCase							(			self     ,A ):
          UpperCAmelCase          =	load_image(inputs["""image"""] )
          UpperCAmelCase          =	inputs["""candidate_labels"""]
          if isinstance(A     ,A ):
                UpperCAmelCase          =	candidate_labels.split(""",""" )

          UpperCAmelCase          =	torch.tensor([[image.height, image.width]]     ,dtype=torch.intaa )
          for i, candidate_label in enumerate(A ):
                UpperCAmelCase          =	self.tokenizer(A     ,return_tensors=self.framework )
                UpperCAmelCase          =	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 ):
          UpperCAmelCase          =	model_inputs.pop("""target_size""" )
          UpperCAmelCase          =	model_inputs.pop("""candidate_label""" )
          UpperCAmelCase          =	model_inputs.pop("""is_last""" )

          UpperCAmelCase          =	self.model(**A )

          UpperCAmelCase          =	{"""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 ):
          UpperCAmelCase          =	[]
          for model_output in model_outputs:
                UpperCAmelCase          =	model_output["""candidate_label"""]
                UpperCAmelCase          =	BaseModelOutput(A )
                UpperCAmelCase          =	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          =	outputs["""scores"""][index].item()
                      UpperCAmelCase          =	self._get_bounding_box(outputs["""boxes"""][index][0] )

                      UpperCAmelCase          =	{"""score""": score, """label""": label, """box""": box}
                      results.append(A )

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

          return results






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











"""simple docstring"""







from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_sentencepiece_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


_UpperCamelCase					      =  {"""configuration_mbart""": ["""MBART_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MBartConfig""", """MBartOnnxConfig"""]}

try:
  if not is_sentencepiece_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  _UpperCamelCase					      =  ["""MBartTokenizer"""]

try:
  if not is_tokenizers_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  _UpperCamelCase					      =  ["""MBartTokenizerFast"""]

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  _UpperCamelCase					      =  [
      """MBART_PRETRAINED_MODEL_ARCHIVE_LIST""",
      """MBartForCausalLM""",
      """MBartForConditionalGeneration""",
      """MBartForQuestionAnswering""",
      """MBartForSequenceClassification""",
      """MBartModel""",
      """MBartPreTrainedModel""",
  ]

try:
  if not is_tf_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  _UpperCamelCase					      =  [
      """TFMBartForConditionalGeneration""",
      """TFMBartModel""",
      """TFMBartPreTrainedModel""",
  ]

try:
  if not is_flax_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  _UpperCamelCase					      =  [
      """FlaxMBartForConditionalGeneration""",
      """FlaxMBartForQuestionAnswering""",
      """FlaxMBartForSequenceClassification""",
      """FlaxMBartModel""",
      """FlaxMBartPreTrainedModel""",
  ]


if TYPE_CHECKING:
  from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig

  try:
    if not is_sentencepiece_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .tokenization_mbart import MBartTokenizer

  try:
    if not is_tokenizers_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .tokenization_mbart_fast import MBartTokenizerFast

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_mbart import (
        MBART_PRETRAINED_MODEL_ARCHIVE_LIST,
        MBartForCausalLM,
        MBartForConditionalGeneration,
        MBartForQuestionAnswering,
        MBartForSequenceClassification,
        MBartModel,
        MBartPreTrainedModel,
    )

  try:
    if not is_tf_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel

  try:
    if not is_flax_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_flax_mbart import (
        FlaxMBartForConditionalGeneration,
        FlaxMBartForQuestionAnswering,
        FlaxMBartForSequenceClassification,
        FlaxMBartModel,
        FlaxMBartPreTrainedModel,
    )

else:
  import sys

  _UpperCamelCase					      =  _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)



