




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 			a__    (					snake_case__      ):






						def __init__(   self		,			**_A			):




											"""simple docstring"""



											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		,			):




											"""simple docstring"""



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

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






						def 				__SCREAMING_SNAKE_CASE(   self		,			**_A			):




											"""simple docstring"""



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






						def 				__SCREAMING_SNAKE_CASE(   self		,			_A			):




											"""simple docstring"""



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

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




											"""simple docstring"""



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

											__lowerCAmelCase				   =       self.model(**_A			)

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






						def 				__SCREAMING_SNAKE_CASE(   self		,			_A		,			_A=0.1		,			_A=None			):




											"""simple docstring"""



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

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

																					__lowerCAmelCase				   =       {"score": score, "label": label, "box": box}
																					results.append(_A			)

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

											return results






						def 				__SCREAMING_SNAKE_CASE(   self		,			_A			):




											"""simple docstring"""



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






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


__lowerCamelCase							=       logging.get_logger(__name__)

__lowerCamelCase							=       {
    # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert
}






class   UpperCAmelCase		(						A_ ):
   A__					:		List[str]						     =     "megatron-bert"



   def __init__(self		:					Optional[int]    ,						snake_case__		:					List[str]=2_90_56    ,						snake_case__		:					List[Any]=10_24    ,						snake_case__		:					str=24    ,						snake_case__		:					Tuple=16    ,						snake_case__		:					Union[str, Any]=40_96    ,						snake_case__		:					str="gelu"    ,						snake_case__		:					str=0.1    ,						snake_case__		:					Optional[int]=0.1    ,						snake_case__		:					Tuple=5_12    ,						snake_case__		:					Union[str, Any]=2    ,						snake_case__		:					Dict=0.02    ,						snake_case__		:					List[Any]=1e-12    ,						snake_case__		:					int=0    ,						snake_case__		:					Tuple="absolute"    ,						snake_case__		:					Any=True    ,						**snake_case__		:					Union[str, Any]    ,						)		->	Optional[Any]:


          '''simple docstring'''


          super().__init__(pad_token_id=snake_case__    ,						**snake_case__ )

          snake_case       :   Tuple							=      vocab_size
          snake_case       :   str							=      hidden_size
          snake_case       :   str							=      num_hidden_layers
          snake_case       :   str							=      num_attention_heads
          snake_case       :   Optional[int]							=      hidden_act
          snake_case       :   int							=      intermediate_size
          snake_case       :   List[str]							=      hidden_dropout_prob
          snake_case       :   Union[str, Any]							=      attention_probs_dropout_prob
          snake_case       :   Dict							=      max_position_embeddings
          snake_case       :   List[str]							=      type_vocab_size
          snake_case       :   List[str]							=      initializer_range
          snake_case       :   Tuple							=      layer_norm_eps
          snake_case       :   int							=      position_embedding_type
          snake_case       :   str							=      use_cache





