


import math
import time

from transformers import Trainer, 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		(_lowerCAmelCase				):




							"""simple docstring"""


							def __init__(							self	:  Optional[Any]   ,     *lowerCamelCase	:  Optional[Any]   ,     lowerCamelCase	:  Dict=None   ,     lowerCamelCase	:  Dict=None   ,     **lowerCamelCase	:  List[str]    )     ->   List[Any]:
														super().__init__(*lowerCamelCase   ,     **lowerCamelCase    )
														__snake_case		:      Optional[Any]										=       eval_examples
														__snake_case		:      Tuple										=       post_process_function

							def    __snake_case (							self	:  Union[str, Any]   ,     lowerCamelCase	:  str=None   ,     lowerCamelCase	:  Dict=None   ,     lowerCamelCase	:  Optional[Any]=None   ,     lowerCamelCase	:  str = "eval"    )     ->   Any:
														__snake_case		:      List[str]										=       self.eval_dataset if eval_dataset is None else eval_dataset
														__snake_case		:      Dict										=       self.get_eval_dataloader(lowerCamelCase    )
														__snake_case		:      Optional[int]										=       self.eval_examples if eval_examples is None else eval_examples

														# Temporarily disable metric computation, we will do it in the loop here.
														__snake_case		:      Optional[int]										=       self.compute_metrics
														__snake_case		:      Any										=       None
														__snake_case		:      Union[str, Any]										=       self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
														__snake_case		:      Union[str, Any]										=       time.time()
														try:
																					__snake_case		:      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:
																					__snake_case		:      List[Any]										=       compute_metrics
														__snake_case		:      List[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
																					__snake_case		:      Optional[int]										=       self.post_process_function(lowerCamelCase   ,     lowerCamelCase   ,     output.predictions    )
																					__snake_case		:      Optional[int]										=       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}_'    ):
																																			__snake_case		:      Optional[Any]										=       metrics.pop(lowerCamelCase    )
																					metrics.update(output.metrics    )
														else:
																					__snake_case		:      int										=       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()    )

														__snake_case		:      Optional[Any]										=       self.callback_handler.on_evaluate(self.args   ,     self.state   ,     self.control   ,     lowerCamelCase    )
														return metrics






							def    __snake_case (							self	:  int   ,     lowerCamelCase	:  List[Any]   ,     lowerCamelCase	:  List[Any]   ,     lowerCamelCase	:  Any=None   ,     lowerCamelCase	:  str = "test"    )     ->   Tuple:
														__snake_case		:      int										=       self.get_test_dataloader(lowerCamelCase    )

														# Temporarily disable metric computation, we will do it in the loop here.
														__snake_case		:      Optional[int]										=       self.compute_metrics
														__snake_case		:      Optional[Any]										=       None
														__snake_case		:      List[Any]										=       self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
														__snake_case		:      int										=       time.time()
														try:
																					__snake_case		:      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:
																					__snake_case		:      Any										=       compute_metrics
														__snake_case		:      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

														__snake_case		:      Optional[int]										=       self.post_process_function(lowerCamelCase   ,     lowerCamelCase   ,     output.predictions   ,     "predict"    )
														__snake_case		:      Union[str, 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}_'    ):
																												__snake_case		:      List[Any]										=       metrics.pop(lowerCamelCase    )
														metrics.update(output.metrics    )
														return PredictionOutput(predictions=predictions.predictions   ,     label_ids=predictions.label_ids   ,     metrics=lowerCamelCase    )





import warnings
from typing import List

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import is_flax_available, is_tf_available, is_torch_available

class     a		(_lowerCAmelCase				):




							"""simple docstring"""


							__UpperCAmelCase   :							List[str]					  =  ["image_processor", "tokenizer"]
							__UpperCAmelCase   :							str					  =  "OwlViTImageProcessor"
							__UpperCAmelCase   :							Dict					  =  ("CLIPTokenizer", "CLIPTokenizerFast")

							def __init__(							self	:  str   ,     lowerCamelCase	:  Any=None   ,     lowerCamelCase	:  Any=None   ,     **lowerCamelCase	:  Union[str, Any]    )     ->   List[Any]:
														__snake_case		:      List[Any]										=       None
														if "feature_extractor" in kwargs:
																					warnings.warn(
																					    "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
																					    " instead."   ,     lowerCamelCase   ,     )
																					__snake_case		:      List[Any]										=       kwargs.pop("feature_extractor"    )

														__snake_case		:      str										=       image_processor if image_processor is not None else feature_extractor
														if image_processor is None:
																					raise ValueError("You need to specify an `image_processor`."    )
														if tokenizer is None:
																					raise ValueError("You need to specify a `tokenizer`."    )

														super().__init__(lowerCamelCase   ,     lowerCamelCase    )

							def __call__(							self	:  Union[str, Any]   ,     lowerCamelCase	:  Tuple=None   ,     lowerCamelCase	:  int=None   ,     lowerCamelCase	:  Union[str, Any]=None   ,     lowerCamelCase	:  List[str]="max_length"   ,     lowerCamelCase	:  Dict="np"   ,     **lowerCamelCase	:  str    )     ->   List[Any]:

														if text is None and query_images is None and images is None:
																					raise ValueError(
																					    "You have to specify at least one text or query image or image. All three cannot be none."    )

														if text is not None:
																					if isinstance(lowerCamelCase   ,     lowerCamelCase    ) or (isinstance(lowerCamelCase   ,     lowerCamelCase    ) and not isinstance(text[0]   ,     lowerCamelCase    )):
																												__snake_case		:      Union[str, Any]										=       [self.tokenizer(lowerCamelCase   ,     padding=lowerCamelCase   ,     return_tensors=lowerCamelCase   ,     **lowerCamelCase    )]

																					elif isinstance(lowerCamelCase   ,     lowerCamelCase    ) and isinstance(text[0]   ,     lowerCamelCase    ):
																												__snake_case		:      Tuple										=       []

																												# Maximum number of queries across batch
																												__snake_case		:      str										=       max([len(lowerCamelCase    ) for t in text]    )

																												# Pad all batch samples to max number of text queries
																												for t in text:
																																			if len(lowerCamelCase    ) != max_num_queries:
																																										__snake_case		:      Dict										=       t + [" "] * (max_num_queries - len(lowerCamelCase    ))

																																			__snake_case		:      int										=       self.tokenizer(lowerCamelCase   ,     padding=lowerCamelCase   ,     return_tensors=lowerCamelCase   ,     **lowerCamelCase    )
																																			encodings.append(lowerCamelCase    )
																					else:
																												raise TypeError("Input text should be a string, a list of strings or a nested list of strings"    )

																					if return_tensors == "np":
																												__snake_case		:      Any										=       np.concatenate([encoding["input_ids"] for encoding in encodings]   ,     axis=0    )
																												__snake_case		:      Tuple										=       np.concatenate([encoding["attention_mask"] for encoding in encodings]   ,     axis=0    )

																					elif return_tensors == "jax" and is_flax_available():
																												import jax.numpy as jnp

																												__snake_case		:      List[Any]										=       jnp.concatenate([encoding["input_ids"] for encoding in encodings]   ,     axis=0    )
																												__snake_case		:      Any										=       jnp.concatenate([encoding["attention_mask"] for encoding in encodings]   ,     axis=0    )

																					elif return_tensors == "pt" and is_torch_available():
																												import torch

																												__snake_case		:      int										=       torch.cat([encoding["input_ids"] for encoding in encodings]   ,     dim=0    )
																												__snake_case		:      int										=       torch.cat([encoding["attention_mask"] for encoding in encodings]   ,     dim=0    )

																					elif return_tensors == "tf" and is_tf_available():
																												import tensorflow as tf

																												__snake_case		:      int										=       tf.stack([encoding["input_ids"] for encoding in encodings]   ,     axis=0    )
																												__snake_case		:      Dict										=       tf.stack([encoding["attention_mask"] for encoding in encodings]   ,     axis=0    )

																					else:
																												raise ValueError("Target return tensor type could not be returned"    )

																					__snake_case		:      Any										=       BatchEncoding()
																					__snake_case		:      Tuple										=       input_ids
																					__snake_case		:      int										=       attention_mask

														if query_images is not None:
																					__snake_case		:      List[Any]										=       BatchEncoding()
																					__snake_case		:      Union[str, Any]										=       self.image_processor(
																					    lowerCamelCase   ,     return_tensors=lowerCamelCase   ,     **lowerCamelCase    ).pixel_values
																					__snake_case		:      str										=       query_pixel_values

														if images is not None:
																					__snake_case		:      Optional[int]										=       self.image_processor(lowerCamelCase   ,     return_tensors=lowerCamelCase   ,     **lowerCamelCase    )

														if text is not None and images is not None:
																					__snake_case		:      List[str]										=       image_features.pixel_values
																					return encoding
														elif query_images is not None and images is not None:
																					__snake_case		:      int										=       image_features.pixel_values
																					return encoding
														elif text is not None or query_images is not None:
																					return encoding
														else:
																					return BatchEncoding(data=dict(**lowerCamelCase    )   ,     tensor_type=lowerCamelCase    )

							def    __snake_case (							self	:  Dict   ,     *lowerCamelCase	:  List[Any]   ,     **lowerCamelCase	:  Union[str, Any]    )     ->   str:
														return self.image_processor.post_process(*lowerCamelCase   ,     **lowerCamelCase    )

							def    __snake_case (							self	:  Union[str, Any]   ,     *lowerCamelCase	:  str   ,     **lowerCamelCase	:  List[str]    )     ->   Tuple:
														return self.image_processor.post_process_object_detection(*lowerCamelCase   ,     **lowerCamelCase    )

							def    __snake_case (							self	:  Optional[Any]   ,     *lowerCamelCase	:  Optional[Any]   ,     **lowerCamelCase	:  Optional[Any]    )     ->   Any:
														return self.image_processor.post_process_image_guided_detection(*lowerCamelCase   ,     **lowerCamelCase    )

							def    __snake_case (							self	:  List[Any]   ,     *lowerCamelCase	:  Tuple   ,     **lowerCamelCase	:  Optional[int]    )     ->   str:
														return self.tokenizer.batch_decode(*lowerCamelCase   ,     **lowerCamelCase    )

							def    __snake_case (							self	:  Union[str, Any]   ,     *lowerCamelCase	:  Tuple   ,     **lowerCamelCase	:  List[Any]    )     ->   Tuple:
														return self.tokenizer.decode(*lowerCamelCase   ,     **lowerCamelCase    )

							@property
							def    __snake_case (							self	:  Any    )     ->   Dict:
														warnings.warn(
														    "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."   ,     lowerCamelCase   ,     )
														return self.image_processor_class






							@property
							def    __snake_case (							self	:  List[str]    )     ->   Union[str, Any]:
														warnings.warn(
														    "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."   ,     lowerCamelCase   ,     )
														return self.image_processor

