


from ...configuration_utils import PretrainedConfig
from ...utils import logging


__lowercase    =				logging.get_logger(__name__)

__lowercase    =				{
    "tiiuae/falcon-40b": "https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json",
    "tiiuae/falcon-7b": "https://huggingface.co/tiiuae/falcon-7b/resolve/main/config.json",
}






class 						_A  (  _UpperCAmelCase  ):







    """simple docstring"""




    UpperCAmelCase	:							int     =	"""falcon"""
    UpperCAmelCase	:							Tuple     =	["""past_key_values"""]






    def __init__( self    :   Optional[Any]    ,			__UpperCAmelCase    :   Tuple=65024    ,			__UpperCAmelCase    :   List[str]=4544    ,			__UpperCAmelCase    :   Optional[Any]=32    ,			__UpperCAmelCase    :   Any=71    ,			__UpperCAmelCase    :   Any=1e-5    ,			__UpperCAmelCase    :   Optional[Any]=0.02    ,			__UpperCAmelCase    :   Dict=True    ,			__UpperCAmelCase    :   str=0.0    ,			__UpperCAmelCase    :   List[str]=0.0    ,			__UpperCAmelCase    :   Optional[Any]=None    ,			__UpperCAmelCase    :   Dict=False    ,			__UpperCAmelCase    :   str=False    ,			__UpperCAmelCase    :   List[str]=True    ,			__UpperCAmelCase    :   Union[str, Any]=True    ,			__UpperCAmelCase    :   str=False    ,			__UpperCAmelCase    :   Optional[int]=11    ,			__UpperCAmelCase    :   Tuple=11    ,			**__UpperCAmelCase    :   List[str]    ,			):
      a						:		Union[str, Any]											=      vocab_size
      # Backward compatibility with n_embed kwarg
      a						:		Optional[int]											=      kwargs.pop("n_embed"    ,			lowercase_)
      a						:		Any											=      hidden_size if n_embed is None else n_embed
      a						:		Any											=      num_hidden_layers
      a						:		Optional[int]											=      num_attention_heads
      a						:		Union[str, Any]											=      layer_norm_epsilon
      a						:		int											=      initializer_range
      a						:		Optional[int]											=      use_cache
      a						:		int											=      hidden_dropout
      a						:		Any											=      attention_dropout

      a						:		List[str]											=      bos_token_id
      a						:		Tuple											=      eos_token_id
      a						:		Tuple											=      num_attention_heads if num_kv_heads is None else num_kv_heads
      a						:		Dict											=      alibi
      a						:		Any											=      new_decoder_architecture
      a						:		Dict											=      multi_query  # Ignored when new_decoder_architecture is True
      a						:		Optional[Any]											=      parallel_attn
      a						:		List[str]											=      bias

      super().__init__(bos_token_id=lowercase_    ,			eos_token_id=lowercase_    ,			**lowercase_)






    @property
    def      __snake_case							( self    :   Tuple):
      return self.hidden_size // self.num_attention_heads






    @property
    def      __snake_case							( self    :   str):
      return not self.alibi










"""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

__lowercase    =				logging.get_logger(__name__)






@add_end_docstrings(_a  )
class 						_A  (  _a  ):







    """simple docstring"""




    def __init__( self    :   List[Any]    ,			**__UpperCAmelCase    :   List[Any]):
      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    :   str    ,			__UpperCAmelCase    :   Union[str, "Image.Image", List[Dict[str, Any]]]    ,			__UpperCAmelCase    :   Union[str, List[str]] = None    ,			**__UpperCAmelCase    :   List[Any]    ,			):
      if "text_queries" in kwargs:
        a						:		List[Any]											=      kwargs.pop("text_queries")

      if isinstance(__UpperCAmelCase    ,			(str, Image.Image)):
        a						:		Any											=      {"image": image, "candidate_labels": candidate_labels}
      else:
        a						:		Optional[int]											=      image
      a						:		Optional[int]											=      super().__call__(__UpperCAmelCase    ,			**__UpperCAmelCase)
      return results






    def      __snake_case							( self    :   Optional[int]    ,			**__UpperCAmelCase    :   List[Any]):
      a						:		str											=      {}
      if "threshold" in kwargs:
        a						:		Dict											=      kwargs["threshold"]
      if "top_k" in kwargs:
        a						:		str											=      kwargs["top_k"]
      return {}, {}, postprocess_params






    def      __snake_case							( self    :   List[Any]    ,			__UpperCAmelCase    :   Optional[Any]):
      a						:		Union[str, Any]											=      load_image(inputs["image"])
      a						:		Any											=      inputs["candidate_labels"]
      if isinstance(__UpperCAmelCase    ,			__UpperCAmelCase):
        a						:		Optional[Any]											=      candidate_labels.split(",")

      a						:		Union[str, Any]											=      torch.tensor([[image.height, image.width]]    ,			dtype=torch.intaa)
      for i, candidate_label in enumerate(__UpperCAmelCase):
        a						:		int											=      self.tokenizer(__UpperCAmelCase    ,			return_tensors=self.framework)
        a						:		int											=      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      __snake_case							( self    :   Dict    ,			__UpperCAmelCase    :   Optional[int]):
      a						:		List[Any]											=      model_inputs.pop("target_size")
      a						:		Optional[int]											=      model_inputs.pop("candidate_label")
      a						:		List[Any]											=      model_inputs.pop("is_last")

      a						:		List[Any]											=      self.model(**__UpperCAmelCase)

      a						:		Union[str, Any]											=      {"target_size": target_size, "candidate_label": candidate_label, "is_last": is_last, **outputs}
      return model_outputs






    def      __snake_case							( self    :   str    ,			__UpperCAmelCase    :   Dict    ,			__UpperCAmelCase    :   Optional[int]=0.1    ,			__UpperCAmelCase    :   List[str]=None):
      a						:		Dict											=      []
      for model_output in model_outputs:
        a						:		int											=      model_output["candidate_label"]
        a						:		Any											=      BaseModelOutput(__UpperCAmelCase)
        a						:		Optional[Any]											=      self.image_processor.post_process_object_detection(
            outputs=__UpperCAmelCase    ,			threshold=__UpperCAmelCase    ,			target_sizes=model_output["target_size"])[0]

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

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

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

      return results






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






