
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		(   __UpperCAmelCase					):







							def __init__(						self  :  int      ,				*snake_case__  :  Optional[int]      ,				snake_case__  :  int=None      ,				snake_case__  :  int=None      ,				**snake_case__  :  List[Any] ):
								"""simple docstring"""







								super().__init__(*snake_case__      ,				**snake_case__ )
								__lowerCAmelCase         =							eval_examples
								__lowerCAmelCase         =							post_process_function







							def       UpperCAmelCase__					(						self  :  List[Any]      ,				snake_case__  :  Optional[Dataset] = None      ,				snake_case__  :  Union[str, Any]=None      ,				snake_case__  :  Optional[List[str]] = None      ,				snake_case__  :  str = "eval"      ,				**snake_case__  :  Union[str, Any]      ,				):
								"""simple docstring"""







								__lowerCAmelCase         =							gen_kwargs.copy()
								__lowerCAmelCase         =							(
								    gen_kwargs["max_length"] if gen_kwargs.get("max_length" ) is not None else self.args.generation_max_length
								)
								__lowerCAmelCase         =							(
								    gen_kwargs["num_beams"] if gen_kwargs.get("num_beams" ) is not None else self.args.generation_num_beams
								)
								__lowerCAmelCase         =							gen_kwargs

								__lowerCAmelCase         =							self.eval_dataset if eval_dataset is None else eval_dataset
								__lowerCAmelCase         =							self.get_eval_dataloader(snake_case__ )
								__lowerCAmelCase         =							self.eval_examples if eval_examples is None else eval_examples

								# Temporarily disable metric computation, we will do it in the loop here.
								__lowerCAmelCase         =							self.compute_metrics
								__lowerCAmelCase         =							None
								__lowerCAmelCase         =							time.time()
								__lowerCAmelCase         =							self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
								try:
									__lowerCAmelCase         =							eval_loop(
									    snake_case__      ,				description="Evaluation"      ,				prediction_loss_only=True if compute_metrics is None else None      ,				ignore_keys=snake_case__      ,				metric_key_prefix=snake_case__      ,				)
								finally:
									__lowerCAmelCase         =							compute_metrics
								__lowerCAmelCase         =							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(
								        snake_case__      ,				snake_case__      ,				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
									__lowerCAmelCase         =							self.post_process_function(snake_case__      ,				snake_case__      ,				snake_case__ )
									__lowerCAmelCase         =							self.compute_metrics(snake_case__ )

									# Prefix all keys with metric_key_prefix + '_'
									for key in list(metrics.keys() ):
										if not key.startswith(F"{metric_key_prefix}_" ):
											__lowerCAmelCase         =							metrics.pop(snake_case__ )

									metrics.update(output.metrics )
								else:
									__lowerCAmelCase         =							output.metrics

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

								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() )

								__lowerCAmelCase         =							self.callback_handler.on_evaluate(self.args      ,				self.state      ,				self.control      ,				snake_case__ )
								return metrics







							def       UpperCAmelCase__					(						self  :  Optional[Any]      ,				snake_case__  :  List[str]      ,				snake_case__  :  Dict      ,				snake_case__  :  List[str]=None      ,				snake_case__  :  str = "test"      ,				**snake_case__  :  List[Any] ):
								"""simple docstring"""







								__lowerCAmelCase         =							gen_kwargs.copy()

								__lowerCAmelCase         =							self.get_test_dataloader(snake_case__ )

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

								__lowerCAmelCase         =							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(
								        snake_case__      ,				snake_case__      ,				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

								__lowerCAmelCase         =							self.post_process_function(snake_case__      ,				snake_case__      ,				snake_case__      ,				"predict" )
								__lowerCAmelCase         =							self.compute_metrics(snake_case__ )

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








from copy import deepcopy
from typing import Optional, Union

import numpy as np

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


if is_torch_available():
					import torch

if is_tf_available():
					import tensorflow as tf

class       a		(   __UpperCAmelCase					):
							lowercase_		:						Tuple   							=  ['image_processor']
							lowercase_		:						Tuple   							=  'SamImageProcessor'







							def __init__(						self  :  List[str]      ,				snake_case__  :  Optional[Any] ):
								"""simple docstring"""







								super().__init__(snake_case__ )
								__lowerCAmelCase         =							self.image_processor
								__lowerCAmelCase         =							-10
								__lowerCAmelCase         =							self.image_processor.size["longest_edge"]







							def __call__(						self  :  Any      ,				snake_case__  :  Optional[int]=None      ,				snake_case__  :  Optional[int]=None      ,				snake_case__  :  str=None      ,				snake_case__  :  List[str]=None      ,				snake_case__  :  Optional[Union[str, TensorType]] = None      ,				**snake_case__  :  Any      ,				):
								"""simple docstring"""







								__lowerCAmelCase         =							self.image_processor(
								    snake_case__      ,				return_tensors=snake_case__      ,				**snake_case__      ,				)

								# pop arguments that are not used in the foward but used nevertheless
								__lowerCAmelCase         =							encoding_image_processor["original_sizes"]

								if hasattr(snake_case__      ,				"numpy" ):  # Checks if Torch or TF tensor
									__lowerCAmelCase         =							original_sizes.numpy()

								__lowerCAmelCase   ,						__lowerCAmelCase   ,						__lowerCAmelCase         =							self._check_and_preprocess_points(
								    input_points=snake_case__      ,				input_labels=snake_case__      ,				input_boxes=snake_case__      ,				)

								__lowerCAmelCase         =							self._normalize_and_convert(
								    snake_case__      ,				snake_case__      ,				input_points=snake_case__      ,				input_labels=snake_case__      ,				input_boxes=snake_case__      ,				return_tensors=snake_case__      ,				)

								return encoding_image_processor







							def       UpperCAmelCase__					(						self  :  Tuple      ,				snake_case__  :  Any      ,				snake_case__  :  Optional[Any]      ,				snake_case__  :  str=None      ,				snake_case__  :  Any=None      ,				snake_case__  :  Any=None      ,				snake_case__  :  List[str]="pt"      ,				):
								"""simple docstring"""







								if input_points is not None:
									if len(snake_case__ ) != len(snake_case__ ):
										__lowerCAmelCase         =							[
										    self._normalize_coordinates(self.target_size      ,				snake_case__      ,				original_sizes[0] ) for point in input_points
										]
									else:
										__lowerCAmelCase         =							[
										    self._normalize_coordinates(self.target_size      ,				snake_case__      ,				snake_case__ )
										    for point, original_size in zip(snake_case__      ,				snake_case__ )
										]
									# check that all arrays have the same shape
									if not all(point.shape == input_points[0].shape for point in input_points ):
										if input_labels is not None:
											__lowerCAmelCase   ,						__lowerCAmelCase         =							self._pad_points_and_labels(snake_case__      ,				snake_case__ )

									__lowerCAmelCase         =							np.array(snake_case__ )

								if input_labels is not None:
									__lowerCAmelCase         =							np.array(snake_case__ )

								if input_boxes is not None:
									if len(snake_case__ ) != len(snake_case__ ):
										__lowerCAmelCase         =							[
										    self._normalize_coordinates(self.target_size      ,				snake_case__      ,				original_sizes[0]      ,				is_bounding_box=snake_case__ )
										    for box in input_boxes
										]
									else:
										__lowerCAmelCase         =							[
										    self._normalize_coordinates(self.target_size      ,				snake_case__      ,				snake_case__      ,				is_bounding_box=snake_case__ )
										    for box, original_size in zip(snake_case__      ,				snake_case__ )
										]
									__lowerCAmelCase         =							np.array(snake_case__ )

								if input_boxes is not None:
									if return_tensors == "pt":
										__lowerCAmelCase         =							torch.from_numpy(snake_case__ )
										# boxes batch size of 1 by default
										__lowerCAmelCase         =							input_boxes.unsqueeze(1 ) if len(input_boxes.shape ) != 3 else input_boxes
									elif return_tensors == "tf":
										__lowerCAmelCase         =							tf.convert_to_tensor(snake_case__ )
										# boxes batch size of 1 by default
										__lowerCAmelCase         =							tf.expand_dims(snake_case__      ,				1 ) if len(input_boxes.shape ) != 3 else input_boxes
									encoding_image_processor.update({"input_boxes": input_boxes} )
								if input_points is not None:
									if return_tensors == "pt":
										__lowerCAmelCase         =							torch.from_numpy(snake_case__ )
										# point batch size of 1 by default
										__lowerCAmelCase         =							input_points.unsqueeze(1 ) if len(input_points.shape ) != 4 else input_points
									elif return_tensors == "tf":
										__lowerCAmelCase         =							tf.convert_to_tensor(snake_case__ )
										# point batch size of 1 by default
										__lowerCAmelCase         =							tf.expand_dims(snake_case__      ,				1 ) if len(input_points.shape ) != 4 else input_points
									encoding_image_processor.update({"input_points": input_points} )
								if input_labels is not None:
									if return_tensors == "pt":
										__lowerCAmelCase         =							torch.from_numpy(snake_case__ )
										# point batch size of 1 by default
										__lowerCAmelCase         =							input_labels.unsqueeze(1 ) if len(input_labels.shape ) != 3 else input_labels
									elif return_tensors == "tf":
										__lowerCAmelCase         =							tf.convert_to_tensor(snake_case__ )
										# point batch size of 1 by default
										__lowerCAmelCase         =							tf.expand_dims(snake_case__      ,				1 ) if len(input_labels.shape ) != 3 else input_labels
									encoding_image_processor.update({"input_labels": input_labels} )

								return encoding_image_processor







							def       UpperCAmelCase__					(						self  :  str      ,				snake_case__  :  Union[str, Any]      ,				snake_case__  :  Dict ):
								"""simple docstring"""







								__lowerCAmelCase         =							max([point.shape[0] for point in input_points] )
								__lowerCAmelCase         =							[]
								for i, point in enumerate(snake_case__ ):
									if point.shape[0] != expected_nb_points:
										__lowerCAmelCase         =							np.concatenate(
										    [point, np.zeros((expected_nb_points - point.shape[0], 2) ) + self.point_pad_value]      ,				axis=0 )
										__lowerCAmelCase         =							np.append(input_labels[i]      ,				[self.point_pad_value] )
									processed_input_points.append(snake_case__ )
								__lowerCAmelCase         =							processed_input_points
								return input_points, input_labels







							def       UpperCAmelCase__					(						self  :  Dict      ,				snake_case__  :  int      ,				snake_case__  :  np.ndarray      ,				snake_case__  :  List[str]      ,				snake_case__  :  Dict=False ):
								"""simple docstring"""







								__lowerCAmelCase   ,						__lowerCAmelCase         =							original_size
								__lowerCAmelCase   ,						__lowerCAmelCase         =							self.image_processor._get_preprocess_shape(snake_case__      ,				longest_edge=snake_case__ )
								__lowerCAmelCase         =							deepcopy(snake_case__ ).astype(snake_case__ )

								if is_bounding_box:
									__lowerCAmelCase         =							coords.reshape(-1      ,				2      ,				2 )

								__lowerCAmelCase         =							coords[..., 0] * (new_w / old_w)
								__lowerCAmelCase         =							coords[..., 1] * (new_h / old_h)

								if is_bounding_box:
									__lowerCAmelCase         =							coords.reshape(-1      ,				4 )

								return coords







							def       UpperCAmelCase__					(						self  :  List[str]      ,				snake_case__  :  Union[str, Any]=None      ,				snake_case__  :  int=None      ,				snake_case__  :  Any=None      ,				):
								"""simple docstring"""







								if input_points is not None:
									if hasattr(snake_case__      ,				"numpy" ):  # Checks for TF or Torch tensor
										__lowerCAmelCase         =							input_points.numpy().tolist()

									if not isinstance(snake_case__      ,				snake_case__ ) or not isinstance(input_points[0]      ,				snake_case__ ):
										raise ValueError("Input points must be a list of list of floating points." )
									__lowerCAmelCase         =							[np.array(snake_case__ ) for input_point in input_points]
								else:
									__lowerCAmelCase         =							None

								if input_labels is not None:
									if hasattr(snake_case__      ,				"numpy" ):
										__lowerCAmelCase         =							input_labels.numpy().tolist()

									if not isinstance(snake_case__      ,				snake_case__ ) or not isinstance(input_labels[0]      ,				snake_case__ ):
										raise ValueError("Input labels must be a list of list integers." )
									__lowerCAmelCase         =							[np.array(snake_case__ ) for label in input_labels]
								else:
									__lowerCAmelCase         =							None

								if input_boxes is not None:
									if hasattr(snake_case__      ,				"numpy" ):
										__lowerCAmelCase         =							input_boxes.numpy().tolist()

									if (
									    not isinstance(snake_case__      ,				snake_case__ )
									    or not isinstance(input_boxes[0]      ,				snake_case__ )
									    or not isinstance(input_boxes[0][0]      ,				snake_case__ )
									):
										raise ValueError("Input boxes must be a list of list of list of floating points." )
									__lowerCAmelCase         =							[np.array(snake_case__ ).astype(np.floataa ) for box in input_boxes]
								else:
									__lowerCAmelCase         =							None

								return input_points, input_labels, input_boxes







							@property
							def       UpperCAmelCase__					(						self  :  Union[str, Any] ):
								"""simple docstring"""







								__lowerCAmelCase         =							self.image_processor.model_input_names
								return list(dict.fromkeys(snake_case__ ) )







							def       UpperCAmelCase__					(						self  :  Optional[Any]      ,				*snake_case__  :  Dict      ,				**snake_case__  :  Union[str, Any] ):
								"""simple docstring"""







								return self.image_processor.post_process_masks(*snake_case__      ,				**snake_case__ )






