



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









import dataclasses
import json
import warnings
from dataclasses import dataclass, field
from time import time
from typing import List

from ..utils import logging


__A       =						logging.get_logger(__name__)



def 	__a					(   lowerCAmelCase_       : Tuple=None      ,lowerCAmelCase_       : Optional[Any]=None    )				->			Tuple:






						'''simple docstring'''



						return field(default_factory=lambda: default      ,metadata=lowerCAmelCase_    )






@dataclass
class 		lowercase						:






	"""simple docstring"""


	a__				: List[str]		       =							list_field(
	    default=[]			,   metadata={
	        "help": (
	            "Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version"
	            " of all available models"
	        )
	    }			,   )

	a__				: List[int]		       =							list_field(
	    default=[8]			,   metadata={"help": "List of batch sizes for which memory and time performance will be evaluated"})

	a__				: List[int]		       =							list_field(
	    default=[8, 32, 128, 512]			,   metadata={"help": "List of sequence lengths for which memory and time performance will be evaluated"}			,   )

	a__				: bool		       =							field(
	    default=snake_case__			,   metadata={"help": "Whether to benchmark inference of model. Inference can be disabled via --no-inference."}			,   )
	a__				: bool		       =							field(
	    default=snake_case__			,   metadata={"help": "Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."}			,   )
	a__				: bool		       =							field(
	    default=snake_case__			,   metadata={"help": "Whether to run on available tpu devices. TPU can be disabled via --no-tpu."})
	a__				: bool		       =							field(default=snake_case__			,   metadata={"help": "Use FP16 to accelerate inference."})
	a__				: bool		       =							field(default=snake_case__			,   metadata={"help": "Benchmark training of model"})
	a__				: bool		       =							field(default=snake_case__			,   metadata={"help": "Verbose memory tracing"})
	a__				: bool		       =							field(
	    default=snake_case__			,   metadata={"help": "Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."}			,   )
	a__				: bool		       =							field(
	    default=snake_case__			,   metadata={
	        "help": "Whether to perform memory measurements. Memory measurements can be disabled via --no-memory"
	    }			,   )
	a__				: bool		       =							field(default=snake_case__			,   metadata={"help": "Trace memory line by line"})
	a__				: bool		       =							field(default=snake_case__			,   metadata={"help": "Save result to a CSV file"})
	a__				: bool		       =							field(default=snake_case__			,   metadata={"help": "Save all print statements in a log file"})
	a__				: bool		       =							field(default=snake_case__			,   metadata={"help": "Whether to print environment information"})
	a__				: bool		       =							field(
	    default=snake_case__			,   metadata={
	        "help": (
	            "Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use"
	            " multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled"
	            " for debugging / testing and on TPU."
	        )
	    }			,   )
	a__				: str		       =							field(
	    default=F'inference_time_{round(time())}.csv'			,   metadata={"help": "CSV filename used if saving time results to csv."}			,   )
	a__				: str		       =							field(
	    default=F'inference_memory_{round(time())}.csv'			,   metadata={"help": "CSV filename used if saving memory results to csv."}			,   )
	a__				: str		       =							field(
	    default=F'train_time_{round(time())}.csv'			,   metadata={"help": "CSV filename used if saving time results to csv for training."}			,   )
	a__				: str		       =							field(
	    default=F'train_memory_{round(time())}.csv'			,   metadata={"help": "CSV filename used if saving memory results to csv for training."}			,   )
	a__				: str		       =							field(
	    default=F'env_info_{round(time())}.csv'			,   metadata={"help": "CSV filename used if saving environment information."}			,   )
	a__				: str		       =							field(
	    default=F'log_{round(time())}.csv'			,   metadata={"help": "Log filename used if print statements are saved in log."}			,   )
	a__				: int		       =							field(default=3			,   metadata={"help": "Times an experiment will be run."})
	a__				: bool		       =							field(
	    default=snake_case__			,   metadata={
	        "help": (
	            "Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain"
	            " model weights."
	        )
	    }			,   )




	def   _SCREAMING_SNAKE_CASE		(     self     :						Optional[int]					)      ->			str:
							warnings.warn(
							    F"""The class {self.__class__} is deprecated. Hugging Face Benchmarking utils"""
							    """ are deprecated in general and it is advised to use external Benchmarking libraries """
							    """ to benchmark Transformer models."""						,  __UpperCAmelCase						,  )




	def   _SCREAMING_SNAKE_CASE		(     self     :						Dict					)      ->			List[str]:
							return json.dumps(dataclasses.asdict(self					)						,  indent=2					)




	@property
	def   _SCREAMING_SNAKE_CASE		(     self     :						List[Any]					)      ->			List[str]:
							if len(self.models					) <= 0:
													raise ValueError(
													    """Please make sure you provide at least one model name / model identifier, *e.g.* `--models"""
													    """ bert-base-cased` or `args.models = ['bert-base-cased']."""					)
							return self.models




	@property
	def   _SCREAMING_SNAKE_CASE		(     self     :						Union[str, Any]					)      ->			Tuple:
							if not self.multi_process:
													return False
							elif self.is_tpu:
													logger.info("""Multiprocessing is currently not possible on TPU."""					)
													return False
							else:
													return True




