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

_snake_case        =    logging.get_logger(__name__)
@add_end_docstrings(_a				)
class 							_SCREAMING_SNAKE_CASE	(	_a				):






				'''simple docstring'''



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







											"""simple docstring"""




											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_						:      Optional[Any]					,  UpperCAmelCase_						:      Union[str, Any] = None					,  **UpperCAmelCase_						:      int					,  )		->	Dict:







											"""simple docstring"""




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

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


				def 					__lowerCamelCase						(       self						:      int					,  **UpperCAmelCase_						:      List[Any]	)		->	Optional[int]:







											"""simple docstring"""




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


				def 					__lowerCamelCase						(       self						:      Tuple					,  UpperCAmelCase_						:      Tuple	)		->	Tuple:







											"""simple docstring"""




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

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







											"""simple docstring"""




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

											_lowerCAmelCase							=      self.model(**UpperCAmelCase_	)

											_lowerCAmelCase							=      {'target_size': target_size, 'candidate_label': candidate_label, 'is_last': is_last, **outputs}
											return model_outputs


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







											"""simple docstring"""




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

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

																									_lowerCAmelCase							=      {'score': score, 'label': label, 'box': box}
																									results.append(UpperCAmelCase_	)

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

											return results







				def 					__lowerCamelCase						(       self						:      Optional[int]					,  UpperCAmelCase_						:      List[Any]	)		->	Dict[str, int]:







											"""simple docstring"""




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










from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


SCREAMING_SNAKE_CASE			: List[Any]				   =					{
    "configuration_poolformer": [
        "POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "PoolFormerConfig",
        "PoolFormerOnnxConfig",
    ]
}

try:
 if not is_vision_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 SCREAMING_SNAKE_CASE			: List[str]				   =					["PoolFormerFeatureExtractor"]
 SCREAMING_SNAKE_CASE			: List[Any]				   =					["PoolFormerImageProcessor"]

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 SCREAMING_SNAKE_CASE			: List[Any]				   =					[
     "POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
     "PoolFormerForImageClassification",
     "PoolFormerModel",
     "PoolFormerPreTrainedModel",
 ]


if TYPE_CHECKING:
 from .configuration_poolformer import (
     POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
     PoolFormerConfig,
     PoolFormerOnnxConfig,
 )

 try:
  if not is_vision_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .feature_extraction_poolformer import PoolFormerFeatureExtractor
  from .image_processing_poolformer import PoolFormerImageProcessor

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_poolformer import (
      POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
      PoolFormerForImageClassification,
      PoolFormerModel,
      PoolFormerPreTrainedModel,
  )


else:
 import sys

 SCREAMING_SNAKE_CASE			: str				   =					_LazyModule(__name__, globals()["__file__"], _import_structure)


