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


@add_end_docstrings(_lowerCamelCase		)
class 		__UpperCAmelCase   (      _lowerCamelCase		):


							def __init__( self					,     **lowerCAmelCase_						):





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





								"""simple docstring"""






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

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


							def 				lowerCamelCase       ( self					,     **lowerCAmelCase_						):





								"""simple docstring"""






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


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_						):





								"""simple docstring"""






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

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





								"""simple docstring"""






								_snake_case     		=	model_inputs.pop('target_size'						)
								_snake_case     		=	model_inputs.pop('candidate_label'						)
								_snake_case     		=	model_inputs.pop('is_last'						)

								_snake_case     		=	self.model(**lowerCAmelCase_						)

								_snake_case     		=	{'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						):





								"""simple docstring"""






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

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

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

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

								return results




							def 				lowerCamelCase       ( self					,     lowerCAmelCase_						):





								"""simple docstring"""






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



'''simple docstring'''







import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
					import torch

if is_vision_available():
					from PIL import Image

					from transformers import GLPNImageProcessor


class 		__UpperCAmelCase   (      unittest.TestCase		):


							def __init__( self					,     lowerCAmelCase_					,     lowerCAmelCase_=7					,     lowerCAmelCase_=3					,     lowerCAmelCase_=18					,     lowerCAmelCase_=30					,     lowerCAmelCase_=4_00					,     lowerCAmelCase_=True					,     lowerCAmelCase_=32					,     lowerCAmelCase_=True					,     ):





								"""simple docstring"""






								_snake_case     		=	parent
								_snake_case     		=	batch_size
								_snake_case     		=	num_channels
								_snake_case     		=	image_size
								_snake_case     		=	min_resolution
								_snake_case     		=	max_resolution
								_snake_case     		=	do_resize
								_snake_case     		=	size_divisor
								_snake_case     		=	do_rescale




							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								return {
								    "do_resize": self.do_resize,
								    "size_divisor": self.size_divisor,
								    "do_rescale": self.do_rescale,
								}


@require_torch
@require_vision
class 		__UpperCAmelCase   (      _lowerCamelCase		,     unittest.TestCase		):
							__lowercase   	= GLPNImageProcessor if is_vision_available() else None


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	GLPNImageProcessingTester(self						)


							@property
							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								return self.image_processor_tester.prepare_image_processor_dict()


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.image_processing_class(**self.image_processor_dict						)
								self.assertTrue(hasattr(lowerCAmelCase_					,     'do_resize'						)						)
								self.assertTrue(hasattr(lowerCAmelCase_					,     'size_divisor'						)						)
								self.assertTrue(hasattr(lowerCAmelCase_					,     'resample'						)						)
								self.assertTrue(hasattr(lowerCAmelCase_					,     'do_rescale'						)						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								pass


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.image_processing_class(**self.image_processor_dict						)
								# create random PIL images
								_snake_case     		=	prepare_image_inputs(self.image_processor_tester					,     equal_resolution=lowerCAmelCase_						)
								for image in image_inputs:
									self.assertIsInstance(lowerCAmelCase_					,     Image.Image						)

								# Test not batched input (GLPNImageProcessor doesn't support batching)
								_snake_case     		=	image_processing(image_inputs[0]					,     return_tensors='pt'						).pixel_values
								self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0						)
								self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.image_processing_class(**self.image_processor_dict						)
								# create random numpy tensors
								_snake_case     		=	prepare_image_inputs(self.image_processor_tester					,     equal_resolution=lowerCAmelCase_					,     numpify=lowerCAmelCase_						)
								for image in image_inputs:
									self.assertIsInstance(lowerCAmelCase_					,     np.ndarray						)

								# Test not batched input (GLPNImageProcessor doesn't support batching)
								_snake_case     		=	image_processing(image_inputs[0]					,     return_tensors='pt'						).pixel_values
								self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0						)
								self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0						)




							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.image_processing_class(**self.image_processor_dict						)
								# create random PyTorch tensors
								_snake_case     		=	prepare_image_inputs(self.image_processor_tester					,     equal_resolution=lowerCAmelCase_					,     torchify=lowerCAmelCase_						)
								for image in image_inputs:
									self.assertIsInstance(lowerCAmelCase_					,     torch.Tensor						)

								# Test not batched input (GLPNImageProcessor doesn't support batching)
								_snake_case     		=	image_processing(image_inputs[0]					,     return_tensors='pt'						).pixel_values
								self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0						)
								self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0						)

