



'''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 	UpperCAmelCase	(		__a):


 '''simple docstring'''




 def __init__(   self							,  **lowerCAmelCase_) ->      Tuple:



      """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							,  lowerCAmelCase_							,  lowerCAmelCase_ = None							,  **lowerCAmelCase_							,  ) ->      str:



      """simple docstring"""







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

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




 def       lowercase_  (   self							,  **lowerCAmelCase_) ->      List[Any]:



      """simple docstring"""







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




 def       lowercase_  (   self							,  lowerCAmelCase_) ->      List[str]:



      """simple docstring"""







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

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



      """simple docstring"""







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

      a_       		=self.model(**lowerCAmelCase_)

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




 def       lowercase_  (   self							,  lowerCAmelCase_							,  lowerCAmelCase_=0.1							,  lowerCAmelCase_=None) ->      str:



      """simple docstring"""







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

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

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

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

      return results




 def       lowercase_  (   self							,  lowerCAmelCase_) ->      Dict[str, int]:



      """simple docstring"""







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







'''simple docstring'''


from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig


lowercase							       =			{
    '''albert-base-v1''': '''https://huggingface.co/albert-base-v1/resolve/main/config.json''',
    '''albert-large-v1''': '''https://huggingface.co/albert-large-v1/resolve/main/config.json''',
    '''albert-xlarge-v1''': '''https://huggingface.co/albert-xlarge-v1/resolve/main/config.json''',
    '''albert-xxlarge-v1''': '''https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json''',
    '''albert-base-v2''': '''https://huggingface.co/albert-base-v2/resolve/main/config.json''',
    '''albert-large-v2''': '''https://huggingface.co/albert-large-v2/resolve/main/config.json''',
    '''albert-xlarge-v2''': '''https://huggingface.co/albert-xlarge-v2/resolve/main/config.json''',
    '''albert-xxlarge-v2''': '''https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json''',
}







class 	UpperCAmelCase	(		__a):


 '''simple docstring'''




 __magic_name__					: int  =      "albert"




 def __init__(   self							,  lowerCAmelCase_=3_0_0_0_0							,  lowerCAmelCase_=1_2_8							,  lowerCAmelCase_=4_0_9_6							,  lowerCAmelCase_=1_2							,  lowerCAmelCase_=1							,  lowerCAmelCase_=6_4							,  lowerCAmelCase_=1_6_3_8_4							,  lowerCAmelCase_=1							,  lowerCAmelCase_="gelu_new"							,  lowerCAmelCase_=0							,  lowerCAmelCase_=0							,  lowerCAmelCase_=5_1_2							,  lowerCAmelCase_=2							,  lowerCAmelCase_=0.0_2							,  lowerCAmelCase_=1e-12							,  lowerCAmelCase_=0.1							,  lowerCAmelCase_="absolute"							,  lowerCAmelCase_=0							,  lowerCAmelCase_=2							,  lowerCAmelCase_=3							,  **lowerCAmelCase_							,  ) ->      Any:



      """simple docstring"""







      super().__init__(pad_token_id=lowerCAmelCase_							,  bos_token_id=lowerCAmelCase_							,  eos_token_id=lowerCAmelCase_							,  **lowerCAmelCase_)

      a_       		=vocab_size
      a_       		=embedding_size
      a_       		=hidden_size
      a_       		=num_hidden_layers
      a_       		=num_hidden_groups
      a_       		=num_attention_heads
      a_       		=inner_group_num
      a_       		=hidden_act
      a_       		=intermediate_size
      a_       		=hidden_dropout_prob
      a_       		=attention_probs_dropout_prob
      a_       		=max_position_embeddings
      a_       		=type_vocab_size
      a_       		=initializer_range
      a_       		=layer_norm_eps
      a_       		=classifier_dropout_prob
      a_       		=position_embedding_type







class 	UpperCAmelCase	(		__a):


 '''simple docstring'''




 @property
 def       lowercase_  (   self) ->      Mapping[str, Mapping[int, str]]:



      """simple docstring"""







      if self.task == "multiple-choice":
           a_       		={0: "batch", 1: "choice", 2: "sequence"}
      else:
           a_       		={0: "batch", 1: "sequence"}
      return OrderedDict(
          [
              ("input_ids", dynamic_axis),
              ("attention_mask", dynamic_axis),
              ("token_type_ids", dynamic_axis),
          ])


