




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




@add_end_docstrings(__UpperCAmelCase			)
class      __UpperCamelCase       (__UpperCAmelCase			):







	def __init__(    self ,				**_lowerCAmelCase						)    ->    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 ,				_lowerCAmelCase ,				_lowerCAmelCase = None ,				**_lowerCAmelCase ,				)    ->    Optional[int]:
							'''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   _a   (    self ,				**_lowerCAmelCase						)    ->    Optional[int]:
							'''simple docstring'''






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







	def   _a   (    self ,				_lowerCAmelCase						)    ->    Union[str, 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   _a   (    self ,				_lowerCAmelCase						)    ->    Tuple:
							'''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   _a   (    self ,				_lowerCAmelCase ,				_lowerCAmelCase=0.1 ,				_lowerCAmelCase=None						)    ->    Optional[int]:
							'''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   _a   (    self ,				_lowerCAmelCase						)    ->    Optional[int]:
							'''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







'''simple docstring'''


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


lowercase_      :				Optional[Any]   					=    logging.get_logger(__name__)

lowercase_      :				int   					=    {
    '''bigcode/gpt_bigcode-santacoder''': '''https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json''',
}




class      __UpperCamelCase       (_UpperCAmelCase			):
	__A			  =					'''gpt_bigcode'''
	__A			  =					['''past_key_values''']
	__A			  =					{
	    '''hidden_size''': '''n_embd''',
	    '''max_position_embeddings''': '''n_positions''',
	    '''num_attention_heads''': '''n_head''',
	    '''num_hidden_layers''': '''n_layer''',
	}







	def __init__(    self ,				_lowerCAmelCase=5_0257 ,				_lowerCAmelCase=1024 ,				_lowerCAmelCase=768 ,				_lowerCAmelCase=12 ,				_lowerCAmelCase=12 ,				_lowerCAmelCase=None ,				_lowerCAmelCase="gelu_pytorch_tanh" ,				_lowerCAmelCase=0.1 ,				_lowerCAmelCase=0.1 ,				_lowerCAmelCase=0.1 ,				_lowerCAmelCase=1E-5 ,				_lowerCAmelCase=0.02 ,				_lowerCAmelCase=True ,				_lowerCAmelCase=True ,				_lowerCAmelCase=5_0256 ,				_lowerCAmelCase=5_0256 ,				_lowerCAmelCase=True ,				_lowerCAmelCase=True ,				_lowerCAmelCase=True ,				**_lowerCAmelCase ,				)    ->    Optional[int]:
							'''simple docstring'''






							lowercase        =							vocab_size
							lowercase        =							n_positions
							lowercase        =							n_embd
							lowercase        =							n_layer
							lowercase        =							n_head
							lowercase        =							n_inner
							lowercase        =							activation_function
							lowercase        =							resid_pdrop
							lowercase        =							embd_pdrop
							lowercase        =							attn_pdrop
							lowercase        =							layer_norm_epsilon
							lowercase        =							initializer_range
							lowercase        =							scale_attn_weights
							lowercase        =							use_cache
							lowercase        =							attention_softmax_in_fpaa
							lowercase        =							scale_attention_softmax_in_fpaa
							lowercase        =							multi_query

							lowercase        =							bos_token_id
							lowercase        =							eos_token_id

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


