



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

__A       =						logging.get_logger(__name__)






@add_end_docstrings(snake_case__)
class 		lowercase						(			snake_case__):






	"""simple docstring"""


	def __init__(     self     :						List[str]						,  **__UpperCAmelCase     :						Optional[Any]					)      ->			int:
							super().__init__(**__UpperCAmelCase					)

							if self.framework == "tf":
													raise ValueError(F"""The {self.__class__} is only available in PyTorch."""					)

							requires_backends(self						,  """vision"""					)
							self.check_model_type(__UpperCAmelCase					)




	def __call__(     self     :						Dict						,  __UpperCAmelCase     :						Union[str, "Image.Image", List[Dict[str, Any]]]						,  __UpperCAmelCase     :						Union[str, List[str]] = None						,  **__UpperCAmelCase     :						List[str]						,  )      ->			List[Any]:
							if "text_queries" in kwargs:
													UpperCAmelCase_=       kwargs.pop("""text_queries"""					)

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




	def   _SCREAMING_SNAKE_CASE		(     self     :						Dict						,  **__UpperCAmelCase     :						List[Any]					)      ->			Optional[int]:
							UpperCAmelCase_=       {}
							if "threshold" in kwargs:
													UpperCAmelCase_=       kwargs["""threshold"""]
							if "top_k" in kwargs:
													UpperCAmelCase_=       kwargs["""top_k"""]
							return {}, {}, postprocess_params




	def   _SCREAMING_SNAKE_CASE		(     self     :						Union[str, Any]						,  __UpperCAmelCase     :						Any					)      ->			str:
							UpperCAmelCase_=       load_image(inputs["""image"""]					)
							UpperCAmelCase_=       inputs["""candidate_labels"""]
							if isinstance(__UpperCAmelCase						,  __UpperCAmelCase					):
													UpperCAmelCase_=       candidate_labels.split(""","""					)

							UpperCAmelCase_=       torch.tensor([[image.height, image.width]]						,  dtype=torch.intaa					)
							for i, candidate_label in enumerate(__UpperCAmelCase					):
													UpperCAmelCase_=       self.tokenizer(__UpperCAmelCase						,  return_tensors=self.framework					)
													UpperCAmelCase_=       self.image_processor(__UpperCAmelCase						,  return_tensors=self.framework					)
													yield {
													    "is_last": i == len(__UpperCAmelCase					) - 1,
													    "target_size": target_size,
													    "candidate_label": candidate_label,
													    **text_inputs,
													    **image_features,
													}




	def   _SCREAMING_SNAKE_CASE		(     self     :						Optional[int]						,  __UpperCAmelCase     :						Optional[Any]					)      ->			Tuple:
							UpperCAmelCase_=       model_inputs.pop("""target_size"""					)
							UpperCAmelCase_=       model_inputs.pop("""candidate_label"""					)
							UpperCAmelCase_=       model_inputs.pop("""is_last"""					)

							UpperCAmelCase_=       self.model(**__UpperCAmelCase					)

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




	def   _SCREAMING_SNAKE_CASE		(     self     :						str						,  __UpperCAmelCase     :						str						,  __UpperCAmelCase     :						Optional[int]=0.1						,  __UpperCAmelCase     :						Optional[int]=None					)      ->			List[str]:
							UpperCAmelCase_=       []
							for model_output in model_outputs:
													UpperCAmelCase_=       model_output["""candidate_label"""]
													UpperCAmelCase_=       BaseModelOutput(__UpperCAmelCase					)
													UpperCAmelCase_=       self.image_processor.post_process_object_detection(
													    outputs=__UpperCAmelCase						,  threshold=__UpperCAmelCase						,  target_sizes=model_output["""target_size"""]					)[0]

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

																			UpperCAmelCase_=       {"""score""": score, """label""": label, """box""": box}
																			results.append(__UpperCAmelCase					)

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

							return results




	def   _SCREAMING_SNAKE_CASE		(     self     :						Optional[Any]						,  __UpperCAmelCase     :						"torch.Tensor"					)      ->			Dict[str, int]:
							if self.framework != "pt":
													raise ValueError("""The ZeroShotObjectDetectionPipeline is only available in PyTorch."""					)
							UpperCAmelCase_,       UpperCAmelCase_,       UpperCAmelCase_,       UpperCAmelCase_=       box.int().tolist()
							UpperCAmelCase_=       {
							    """xmin""": xmin,
							    """ymin""": ymin,
							    """xmax""": xmax,
							    """ymax""": ymax,
							}
							return bbox









from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


__A       =						{
    '''configuration_clip''': [
        '''CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''CLIPConfig''',
        '''CLIPOnnxConfig''',
        '''CLIPTextConfig''',
        '''CLIPVisionConfig''',
    ],
    '''processing_clip''': ['''CLIPProcessor'''],
    '''tokenization_clip''': ['''CLIPTokenizer'''],
}

try:
	if not is_tokenizers_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__A       =						['''CLIPTokenizerFast''']

try:
	if not is_vision_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__A       =						['''CLIPFeatureExtractor''']
	__A       =						['''CLIPImageProcessor''']

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__A       =						[
	    '''CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
	    '''CLIPModel''',
	    '''CLIPPreTrainedModel''',
	    '''CLIPTextModel''',
	    '''CLIPTextModelWithProjection''',
	    '''CLIPVisionModel''',
	    '''CLIPVisionModelWithProjection''',
	]

try:
	if not is_tf_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__A       =						[
	    '''TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
	    '''TFCLIPModel''',
	    '''TFCLIPPreTrainedModel''',
	    '''TFCLIPTextModel''',
	    '''TFCLIPVisionModel''',
	]

try:
	if not is_flax_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__A       =						[
	    '''FlaxCLIPModel''',
	    '''FlaxCLIPPreTrainedModel''',
	    '''FlaxCLIPTextModel''',
	    '''FlaxCLIPTextPreTrainedModel''',
	    '''FlaxCLIPVisionModel''',
	    '''FlaxCLIPVisionPreTrainedModel''',
	]


if TYPE_CHECKING:
	from .configuration_clip import (
	    CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
	    CLIPConfig,
	    CLIPOnnxConfig,
	    CLIPTextConfig,
	    CLIPVisionConfig,
	)
	from .processing_clip import CLIPProcessor
	from .tokenization_clip import CLIPTokenizer

	try:
		if not is_tokenizers_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .tokenization_clip_fast import CLIPTokenizerFast

	try:
		if not is_vision_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .feature_extraction_clip import CLIPFeatureExtractor
		from .image_processing_clip import CLIPImageProcessor

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_clip import (
		    CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
		    CLIPModel,
		    CLIPPreTrainedModel,
		    CLIPTextModel,
		    CLIPTextModelWithProjection,
		    CLIPVisionModel,
		    CLIPVisionModelWithProjection,
		)

	try:
		if not is_tf_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_tf_clip import (
		    TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
		    TFCLIPModel,
		    TFCLIPPreTrainedModel,
		    TFCLIPTextModel,
		    TFCLIPVisionModel,
		)

	try:
		if not is_flax_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_flax_clip import (
		    FlaxCLIPModel,
		    FlaxCLIPPreTrainedModel,
		    FlaxCLIPTextModel,
		    FlaxCLIPTextPreTrainedModel,
		    FlaxCLIPVisionModel,
		    FlaxCLIPVisionPreTrainedModel,
		)


else:
	import sys

	__A       =						_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)




