





'''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

lowerCAmelCase_   :       Dict       =     logging.get_logger(__name__)
@add_end_docstrings(SCREAMING_SNAKE_CASE__ )
class 							__SCREAMING_SNAKE_CASE    (SCREAMING_SNAKE_CASE__ ):






				"""simple docstring"""







				def __init__(    self	:   Tuple   ,							**__a	:   List[str]   ):
								super().__init__(**_lowercase   )

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

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




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

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




				def     UpperCamelCase__  (    self	:   Optional[Any]   ,							**__a	:   int   ):
								_a				      =					{}
								if "threshold" in kwargs:
												_a				      =					kwargs["threshold"]
								if "top_k" in kwargs:
												_a				      =					kwargs["top_k"]
								return {}, {}, postprocess_params




				def     UpperCamelCase__  (    self	:   List[str]   ,							__a	:   str   ):
								_a				      =					load_image(inputs["image"]   )
								_a				      =					inputs["candidate_labels"]
								if isinstance(_lowercase   ,							_lowercase   ):
												_a				      =					candidate_labels.split(","   )

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




				def     UpperCamelCase__  (    self	:   int   ,							__a	:   Optional[Any]   ):
								_a				      =					model_inputs.pop("target_size"   )
								_a				      =					model_inputs.pop("candidate_label"   )
								_a				      =					model_inputs.pop("is_last"   )

								_a				      =					self.model(**_lowercase   )

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




				def     UpperCamelCase__  (    self	:   Union[str, Any]   ,							__a	:   Optional[int]   ,							__a	:   Optional[Any]=0.1   ,							__a	:   Any=None   ):
								_a				      =					[]
								for model_output in model_outputs:
												_a				      =					model_output["candidate_label"]
												_a				      =					BaseModelOutput(_lowercase   )
												_a				      =					self.image_processor.post_process_object_detection(
												    outputs=_lowercase   ,							threshold=_lowercase   ,							target_sizes=model_output["target_size"]   )[0]

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

																_a				      =					{"score": score, "label": label, "box": box}
																results.append(_lowercase   )

								_a				      =					sorted(_lowercase   ,							key=lambda __a   : x["score"]   ,							reverse=_lowercase   )
								if top_k:
												_a				      =					results[:top_k]

								return results




				def     UpperCamelCase__  (    self	:   List[Any]   ,							__a	:   "torch.Tensor"   ):
								if self.framework != "pt":
												raise ValueError("The ZeroShotObjectDetectionPipeline is only available in PyTorch."   )
								_a				      =					box.int().tolist()
								_a				      =					{
								    "xmin": xmin,
								    "ymin": ymin,
								    "xmax": xmax,
								    "ymax": ymax,
								}
								return bbox





"""simple docstring"""







from typing import TYPE_CHECKING

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


A		=						{'configuration_vit': ['VIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTConfig', 'ViTOnnxConfig']}

try:
			if not is_vision_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			A		=						['ViTFeatureExtractor']
			A		=						['ViTImageProcessor']

try:
			if not is_torch_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			A		=						[
			    'VIT_PRETRAINED_MODEL_ARCHIVE_LIST',
			    'ViTForImageClassification',
			    'ViTForMaskedImageModeling',
			    'ViTModel',
			    'ViTPreTrainedModel',
			]

try:
			if not is_tf_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			A		=						[
			    'TFViTForImageClassification',
			    'TFViTModel',
			    'TFViTPreTrainedModel',
			]

try:
			if not is_flax_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			A		=						[
			    'FlaxViTForImageClassification',
			    'FlaxViTModel',
			    'FlaxViTPreTrainedModel',
			]

if TYPE_CHECKING:
			from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig

			try:
						if not is_vision_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .feature_extraction_vit import ViTFeatureExtractor
						from .image_processing_vit import ViTImageProcessor

			try:
						if not is_torch_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_vit import (
						    VIT_PRETRAINED_MODEL_ARCHIVE_LIST,
						    ViTForImageClassification,
						    ViTForMaskedImageModeling,
						    ViTModel,
						    ViTPreTrainedModel,
						)

			try:
						if not is_tf_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel

			try:
						if not is_flax_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel


else:
			import sys

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



