



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



@add_end_docstrings(__UpperCAmelCase)
class  lowerCamelCase__    (							__UpperCAmelCase):




		'''simple docstring'''



		def __init__(self	,**__lowerCamelCase				)  ->    List[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	,)  ->    Any:

						"""simple docstring"""






						if "text_queries" in kwargs:
										lowerCAmelCase__  :       str				=  kwargs.pop('''text_queries'''				)

						if isinstance(lowerCAmelCase_	,(str, Image.Image)				):
										lowerCAmelCase__  :       Optional[int]				=  {'''image''': image, '''candidate_labels''': candidate_labels}
						else:
										lowerCAmelCase__  :       str				=  image
						lowerCAmelCase__  :       str				=  super().__call__(lowerCAmelCase_	,**lowerCAmelCase_				)
						return results



		def 	lowerCAmelCase__   (self	,**__lowerCamelCase				)  ->    Tuple:

						"""simple docstring"""






						lowerCAmelCase__  :       List[str]				=  {}
						if "threshold" in kwargs:
										lowerCAmelCase__  :       Dict				=  kwargs['''threshold''']
						if "top_k" in kwargs:
										lowerCAmelCase__  :       Dict				=  kwargs['''top_k''']
						return {}, {}, postprocess_params



		def 	lowerCAmelCase__   (self	,__lowerCamelCase				)  ->    Union[str, Any]:

						"""simple docstring"""






						lowerCAmelCase__  :       List[Any]				=  load_image(inputs['''image''']				)
						lowerCAmelCase__  :       Union[str, Any]				=  inputs['''candidate_labels''']
						if isinstance(lowerCAmelCase_	,lowerCAmelCase_				):
										lowerCAmelCase__  :       Any				=  candidate_labels.split(''','''				)

						lowerCAmelCase__  :       Tuple				=  torch.tensor([[image.height, image.width]]	,dtype=torch.intaa				)
						for i, candidate_label in enumerate(lowerCAmelCase_				):
										lowerCAmelCase__  :       Any				=  self.tokenizer(lowerCAmelCase_	,return_tensors=self.framework				)
										lowerCAmelCase__  :       Union[str, Any]				=  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 	lowerCAmelCase__   (self	,__lowerCamelCase				)  ->    int:

						"""simple docstring"""






						lowerCAmelCase__  :       List[str]				=  model_inputs.pop('''target_size'''				)
						lowerCAmelCase__  :       List[str]				=  model_inputs.pop('''candidate_label'''				)
						lowerCAmelCase__  :       Tuple				=  model_inputs.pop('''is_last'''				)

						lowerCAmelCase__  :       str				=  self.model(**lowerCAmelCase_				)

						lowerCAmelCase__  :       List[Any]				=  {'''target_size''': target_size, '''candidate_label''': candidate_label, '''is_last''': is_last, **outputs}
						return model_outputs



		def 	lowerCAmelCase__   (self	,__lowerCamelCase	,__lowerCamelCase=0.1	,__lowerCamelCase=None				)  ->    List[str]:

						"""simple docstring"""






						lowerCAmelCase__  :       int				=  []
						for model_output in model_outputs:
										lowerCAmelCase__  :       Dict				=  model_output['''candidate_label''']
										lowerCAmelCase__  :       Any				=  BaseModelOutput(lowerCAmelCase_				)
										lowerCAmelCase__  :       Tuple				=  self.image_processor.post_process_object_detection(
										    outputs=lowerCAmelCase_	,threshold=lowerCAmelCase_	,target_sizes=model_output['''target_size''']				)[0]

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

														lowerCAmelCase__  :       Dict				=  {'''score''': score, '''label''': label, '''box''': box}
														results.append(lowerCAmelCase_				)

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

						return results



		def 	lowerCAmelCase__   (self	,__lowerCamelCase				)  ->    Optional[int]:

						"""simple docstring"""






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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	int):





				'''simple docstring'''

				if not isinstance(lowerCamelCase_ ,lowerCamelCase_):
								lowerCAmelCase__  :       Dict				=  f"""Input value of [number={number}] must be an integer"""
								raise TypeError(lowerCamelCase_)

				if number < 1:
								lowerCAmelCase__  :       Any				=  f"""Input value of [number={number}] must be > 0"""
								raise ValueError(lowerCamelCase_)

				lowerCAmelCase__  :       List[str]				=  1

				for i in range(1 ,lowerCamelCase_):
								current_number *= 4 * i - 2
								current_number //= i + 1

				return current_number


if __name__ == "__main__":
							import doctest

							doctest.testmod()

