


import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
 import torch_xla.core.xla_model as xm
 import torch_xla.debug.metrics as met






class 						_A  (  _a  ):







    """simple docstring"""




    def __init__( self    :   List[Any]    ,			*__UpperCAmelCase    :   Any    ,			__UpperCAmelCase    :   Union[str, Any]=None    ,			__UpperCAmelCase    :   Union[str, Any]=None    ,			**__UpperCAmelCase    :   Optional[Any]):
      super().__init__(*__lowerCAmelCase    ,			**__lowerCAmelCase)
      a						:		List[Any]											=      eval_examples
      a						:		Optional[Any]											=      post_process_function






    def      __snake_case							( self    :   Optional[Any]    ,			__UpperCAmelCase    :   List[str] = None    ,			__UpperCAmelCase    :   Union[str, Any]=None    ,			__UpperCAmelCase    :   List[str] = None    ,			__UpperCAmelCase    :   Tuple = "eval"    ,			**__UpperCAmelCase    :   int    ,			):
      a						:		Union[str, Any]											=      gen_kwargs.copy()
      a						:		Tuple											=      (
          gen_kwargs["max_length"] if gen_kwargs.get("max_length") is not None else self.args.generation_max_length
      )
      a						:		Any											=      (
          gen_kwargs["num_beams"] if gen_kwargs.get("num_beams") is not None else self.args.generation_num_beams
      )
      a						:		Dict											=      gen_kwargs

      a						:		List[Any]											=      self.eval_dataset if eval_dataset is None else eval_dataset
      a						:		int											=      self.get_eval_dataloader(__lowerCAmelCase)
      a						:		int											=      self.eval_examples if eval_examples is None else eval_examples

      # Temporarily disable metric computation, we will do it in the loop here.
      a						:		Tuple											=      self.compute_metrics
      a						:		Optional[int]											=      None
      a						:		int											=      time.time()
      a						:		Tuple											=      self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
      try:
        a						:		Union[str, Any]											=      eval_loop(
            __lowerCAmelCase    ,			description="Evaluation"    ,			prediction_loss_only=True if compute_metrics is None else None    ,			ignore_keys=__lowerCAmelCase    ,			metric_key_prefix=__lowerCAmelCase    ,			)
      finally:
        a						:		Optional[int]											=      compute_metrics
      a						:		str											=      self.args.eval_batch_size * self.args.world_size
      if f'''{metric_key_prefix}_jit_compilation_time''' in output.metrics:
        start_time += output.metrics[f'''{metric_key_prefix}_jit_compilation_time''']
      output.metrics.update(
          speed_metrics(
              __lowerCAmelCase    ,			__lowerCAmelCase    ,			num_samples=output.num_samples    ,			num_steps=math.ceil(output.num_samples / total_batch_size)    ,			))

      if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
        # Only the main node write the results by default
        a						:		Optional[int]											=      self.post_process_function(__lowerCAmelCase    ,			__lowerCAmelCase    ,			__lowerCAmelCase)
        a						:		Tuple											=      self.compute_metrics(__lowerCAmelCase)

        # Prefix all keys with metric_key_prefix + '_'
        for key in list(metrics.keys()):
          if not key.startswith(f'''{metric_key_prefix}_'''):
            a						:		Optional[int]											=      metrics.pop(__lowerCAmelCase)

        metrics.update(output.metrics)
      else:
        a						:		List[Any]											=      output.metrics

      if self.args.should_log:
        # Only the main node log the results by default
        self.log(__lowerCAmelCase)

      if self.args.tpu_metrics_debug or self.args.debug:
        # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
        xm.master_print(met.metrics_report())

      a						:		List[str]											=      self.callback_handler.on_evaluate(self.args    ,			self.state    ,			self.control    ,			__lowerCAmelCase)
      return metrics






    def      __snake_case							( self    :   Union[str, Any]    ,			__UpperCAmelCase    :   List[str]    ,			__UpperCAmelCase    :   Dict    ,			__UpperCAmelCase    :   Tuple=None    ,			__UpperCAmelCase    :   str = "test"    ,			**__UpperCAmelCase    :   Optional[int]):
      a						:		Optional[Any]											=      gen_kwargs.copy()

      a						:		Any											=      self.get_test_dataloader(__lowerCAmelCase)

      # Temporarily disable metric computation, we will do it in the loop here.
      a						:		Optional[int]											=      self.compute_metrics
      a						:		Any											=      None
      a						:		Tuple											=      time.time()
      a						:		Dict											=      self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
      try:
        a						:		Optional[int]											=      eval_loop(
            __lowerCAmelCase    ,			description="Prediction"    ,			prediction_loss_only=True if compute_metrics is None else None    ,			ignore_keys=__lowerCAmelCase    ,			metric_key_prefix=__lowerCAmelCase    ,			)
      finally:
        a						:		List[Any]											=      compute_metrics

      a						:		Union[str, Any]											=      self.args.eval_batch_size * self.args.world_size
      if f'''{metric_key_prefix}_jit_compilation_time''' in output.metrics:
        start_time += output.metrics[f'''{metric_key_prefix}_jit_compilation_time''']
      output.metrics.update(
          speed_metrics(
              __lowerCAmelCase    ,			__lowerCAmelCase    ,			num_samples=output.num_samples    ,			num_steps=math.ceil(output.num_samples / total_batch_size)    ,			))
      if self.post_process_function is None or self.compute_metrics is None:
        return output

      a						:		Dict											=      self.post_process_function(__lowerCAmelCase    ,			__lowerCAmelCase    ,			__lowerCAmelCase    ,			"predict")
      a						:		List[Any]											=      self.compute_metrics(__lowerCAmelCase)

      # Prefix all keys with metric_key_prefix + '_'
      for key in list(metrics.keys()):
        if not key.startswith(f'''{metric_key_prefix}_'''):
          a						:		str											=      metrics.pop(__lowerCAmelCase)
      metrics.update(output.metrics)
      return PredictionOutput(predictions=predictions.predictions    ,			label_ids=predictions.label_ids    ,			metrics=__lowerCAmelCase)










"""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    =				logging.get_logger(__name__)






@add_end_docstrings(_a  )
class 						_A  (  _a  ):







    """simple docstring"""




    def __init__( self    :   List[Any]    ,			**__UpperCAmelCase    :   List[Any]):
      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    :   str    ,			__UpperCAmelCase    :   Union[str, "Image.Image", List[Dict[str, Any]]]    ,			__UpperCAmelCase    :   Union[str, List[str]] = None    ,			**__UpperCAmelCase    :   List[Any]    ,			):
      if "text_queries" in kwargs:
        a						:		List[Any]											=      kwargs.pop("text_queries")

      if isinstance(__UpperCAmelCase    ,			(str, Image.Image)):
        a						:		Any											=      {"image": image, "candidate_labels": candidate_labels}
      else:
        a						:		Optional[int]											=      image
      a						:		Optional[int]											=      super().__call__(__UpperCAmelCase    ,			**__UpperCAmelCase)
      return results






    def      __snake_case							( self    :   Optional[int]    ,			**__UpperCAmelCase    :   List[Any]):
      a						:		str											=      {}
      if "threshold" in kwargs:
        a						:		Dict											=      kwargs["threshold"]
      if "top_k" in kwargs:
        a						:		str											=      kwargs["top_k"]
      return {}, {}, postprocess_params






    def      __snake_case							( self    :   List[Any]    ,			__UpperCAmelCase    :   Optional[Any]):
      a						:		Union[str, Any]											=      load_image(inputs["image"])
      a						:		Any											=      inputs["candidate_labels"]
      if isinstance(__UpperCAmelCase    ,			__UpperCAmelCase):
        a						:		Optional[Any]											=      candidate_labels.split(",")

      a						:		Union[str, Any]											=      torch.tensor([[image.height, image.width]]    ,			dtype=torch.intaa)
      for i, candidate_label in enumerate(__UpperCAmelCase):
        a						:		int											=      self.tokenizer(__UpperCAmelCase    ,			return_tensors=self.framework)
        a						:		int											=      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      __snake_case							( self    :   Dict    ,			__UpperCAmelCase    :   Optional[int]):
      a						:		List[Any]											=      model_inputs.pop("target_size")
      a						:		Optional[int]											=      model_inputs.pop("candidate_label")
      a						:		List[Any]											=      model_inputs.pop("is_last")

      a						:		List[Any]											=      self.model(**__UpperCAmelCase)

      a						:		Union[str, Any]											=      {"target_size": target_size, "candidate_label": candidate_label, "is_last": is_last, **outputs}
      return model_outputs






    def      __snake_case							( self    :   str    ,			__UpperCAmelCase    :   Dict    ,			__UpperCAmelCase    :   Optional[int]=0.1    ,			__UpperCAmelCase    :   List[str]=None):
      a						:		Dict											=      []
      for model_output in model_outputs:
        a						:		int											=      model_output["candidate_label"]
        a						:		Any											=      BaseModelOutput(__UpperCAmelCase)
        a						:		Optional[Any]											=      self.image_processor.post_process_object_detection(
            outputs=__UpperCAmelCase    ,			threshold=__UpperCAmelCase    ,			target_sizes=model_output["target_size"])[0]

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

          a						:		Optional[Any]											=      {"score": score, "label": label, "box": box}
          results.append(__UpperCAmelCase)

      a						:		str											=      sorted(__UpperCAmelCase    ,			key=lambda __UpperCAmelCase: x["score"]    ,			reverse=__UpperCAmelCase)
      if top_k:
        a						:		Union[str, Any]											=      results[:top_k]

      return results






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






