



'''simple docstring'''





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 					snake_case			(UpperCamelCase ):
       lowerCAmelCase__	:Union[str, Any]     =       ["image_processor"]
       lowerCAmelCase__	:Union[str, Any]     =       "SamImageProcessor"



       def __init__(					self  ,UpperCAmelCase_   )	->				Optional[int]:
           super().__init__(UpperCAmelCase_   )
           lowercase__									=    self.image_processor
           lowercase__									=    -10
           lowercase__									=    self.image_processor.size["longest_edge"]



       def __call__(					self  ,UpperCAmelCase_=None  ,UpperCAmelCase_=None  ,UpperCAmelCase_=None  ,UpperCAmelCase_=None  ,UpperCAmelCase_ = None  ,**UpperCAmelCase_  ,)	->				BatchEncoding:
           lowercase__									=    self.image_processor(
               UpperCAmelCase_  ,return_tensors=UpperCAmelCase_  ,**UpperCAmelCase_  ,)

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

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

           lowercase__							,							lowercase__							,							lowercase__									=    self._check_and_preprocess_points(
               input_points=UpperCAmelCase_  ,input_labels=UpperCAmelCase_  ,input_boxes=UpperCAmelCase_  ,)

           lowercase__									=    self._normalize_and_convert(
               UpperCAmelCase_  ,UpperCAmelCase_  ,input_points=UpperCAmelCase_  ,input_labels=UpperCAmelCase_  ,input_boxes=UpperCAmelCase_  ,return_tensors=UpperCAmelCase_  ,)

           return encoding_image_processor



       def 				_a   (					self  ,UpperCAmelCase_  ,UpperCAmelCase_  ,UpperCAmelCase_=None  ,UpperCAmelCase_=None  ,UpperCAmelCase_=None  ,UpperCAmelCase_="pt"  ,)	->				List[Any]:
           if input_points is not None:
               if len(UpperCAmelCase_   ) != len(UpperCAmelCase_   ):
                   lowercase__									=    [
                       self._normalize_coordinates(self.target_size  ,UpperCAmelCase_  ,original_sizes[0]   ) for point in input_points
                   ]
               else:
                   lowercase__									=    [
                       self._normalize_coordinates(self.target_size  ,UpperCAmelCase_  ,UpperCAmelCase_   )
                       for point, original_size in zip(UpperCAmelCase_  ,UpperCAmelCase_   )
                   ]
               # 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:
                       lowercase__							,							lowercase__									=    self._pad_points_and_labels(UpperCAmelCase_  ,UpperCAmelCase_   )

               lowercase__									=    np.array(UpperCAmelCase_   )

           if input_labels is not None:
               lowercase__									=    np.array(UpperCAmelCase_   )

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

           if input_boxes is not None:
               if return_tensors == "pt":
                   lowercase__									=    torch.from_numpy(UpperCAmelCase_   )
                   # boxes batch size of 1 by default
                   lowercase__									=    input_boxes.unsqueeze(1   ) if len(input_boxes.shape   ) != 3 else input_boxes
               elif return_tensors == "tf":
                   lowercase__									=    tf.convert_to_tensor(UpperCAmelCase_   )
                   # boxes batch size of 1 by default
                   lowercase__									=    tf.expand_dims(UpperCAmelCase_  ,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":
                   lowercase__									=    torch.from_numpy(UpperCAmelCase_   )
                   # point batch size of 1 by default
                   lowercase__									=    input_points.unsqueeze(1   ) if len(input_points.shape   ) != 4 else input_points
               elif return_tensors == "tf":
                   lowercase__									=    tf.convert_to_tensor(UpperCAmelCase_   )
                   # point batch size of 1 by default
                   lowercase__									=    tf.expand_dims(UpperCAmelCase_  ,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":
                   lowercase__									=    torch.from_numpy(UpperCAmelCase_   )
                   # point batch size of 1 by default
                   lowercase__									=    input_labels.unsqueeze(1   ) if len(input_labels.shape   ) != 3 else input_labels
               elif return_tensors == "tf":
                   lowercase__									=    tf.convert_to_tensor(UpperCAmelCase_   )
                   # point batch size of 1 by default
                   lowercase__									=    tf.expand_dims(UpperCAmelCase_  ,1   ) if len(input_labels.shape   ) != 3 else input_labels
               encoding_image_processor.update({"input_labels": input_labels}   )

           return encoding_image_processor



       def 				_a   (					self  ,UpperCAmelCase_  ,UpperCAmelCase_   )	->				Optional[Any]:
           lowercase__									=    max([point.shape[0] for point in input_points]   )
           lowercase__									=    []
           for i, point in enumerate(UpperCAmelCase_   ):
               if point.shape[0] != expected_nb_points:
                   lowercase__									=    np.concatenate(
                       [point, np.zeros((expected_nb_points - point.shape[0], 2)   ) + self.point_pad_value]  ,axis=0   )
                   lowercase__									=    np.append(input_labels[i]  ,[self.point_pad_value]   )
               processed_input_points.append(UpperCAmelCase_   )
           lowercase__									=    processed_input_points
           return input_points, input_labels



       def 				_a   (					self  ,UpperCAmelCase_  ,UpperCAmelCase_  ,UpperCAmelCase_  ,UpperCAmelCase_=False   )	->				np.ndarray:
           lowercase__							,							lowercase__									=    original_size
           lowercase__							,							lowercase__									=    self.image_processor._get_preprocess_shape(UpperCAmelCase_  ,longest_edge=UpperCAmelCase_   )
           lowercase__									=    deepcopy(UpperCAmelCase_   ).astype(UpperCAmelCase_   )

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

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

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

           return coords



       def 				_a   (					self  ,UpperCAmelCase_=None  ,UpperCAmelCase_=None  ,UpperCAmelCase_=None  ,)	->				Union[str, Any]:
           if input_points is not None:
               if hasattr(UpperCAmelCase_  ,"numpy"   ):  # Checks for TF or Torch tensor
                   lowercase__									=    input_points.numpy().tolist()

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

           if input_labels is not None:
               if hasattr(UpperCAmelCase_  ,"numpy"   ):
                   lowercase__									=    input_labels.numpy().tolist()

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

           if input_boxes is not None:
               if hasattr(UpperCAmelCase_  ,"numpy"   ):
                   lowercase__									=    input_boxes.numpy().tolist()

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

           return input_points, input_labels, input_boxes



       @property
       def 				_a   (					self   )	->				List[str]:
           lowercase__									=    self.image_processor.model_input_names
           return list(dict.fromkeys(UpperCAmelCase_   )   )







       def 				_a   (					self  ,*UpperCAmelCase_  ,**UpperCAmelCase_   )	->				int:
           return self.image_processor.post_process_masks(*UpperCAmelCase_  ,**UpperCAmelCase_   )









'''simple docstring'''





from sklearn.metrics import mean_squared_error

import datasets


SCREAMING_SNAKE_CASE__          =  "\\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n"

SCREAMING_SNAKE_CASE__          =  "\\nMean Squared Error(MSE) is the average of the square of difference between the predicted\nand actual values.\n"


SCREAMING_SNAKE_CASE__          =  "\nArgs:\n    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)\n        Estimated target values.\n    references: array-like of shape (n_samples,) or (n_samples, n_outputs)\n        Ground truth (correct) target values.\n    sample_weight: array-like of shape (n_samples,), default=None\n        Sample weights.\n    multioutput: {\"raw_values\", \"uniform_average\"} or array-like of shape (n_outputs,), default=\"uniform_average\"\n        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.\n\n        \"raw_values\" : Returns a full set of errors in case of multioutput input.\n\n        \"uniform_average\" : Errors of all outputs are averaged with uniform weight.\n\n    squared : bool, default=True\n        If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.\n\nReturns:\n    mse : mean squared error.\nExamples:\n\n    >>> mse_metric = datasets.load_metric(\"mse\")\n    >>> predictions = [2.5, 0.0, 2, 8]\n    >>> references = [3, -0.5, 2, 7]\n    >>> results = mse_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'mse': 0.375}\n    >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)\n    >>> print(rmse_result)\n    {'mse': 0.6123724356957945}\n\n    If you're using multi-dimensional lists, then set the config as follows :\n\n    >>> mse_metric = datasets.load_metric(\"mse\", \"multilist\")\n    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]\n    >>> references = [[0, 2], [-1, 2], [8, -5]]\n    >>> results = mse_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'mse': 0.7083333333333334}\n    >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput='raw_values')\n    >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n    {'mse': array([0.41666667, 1. ])}\n"


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION		,   _KWARGS_DESCRIPTION )
class 					snake_case			(datasets.Metric ):



       def 				_a   (					self   )	->				Optional[int]:
           return datasets.MetricInfo(
               description=_DESCRIPTION  ,citation=_CITATION  ,inputs_description=_KWARGS_DESCRIPTION  ,features=datasets.Features(self._get_feature_types()   )  ,reference_urls=[
                   "https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html"
               ]  ,)



       def 				_a   (					self   )	->				Tuple:
           if self.config_name == "multilist":
               return {
                   "predictions": datasets.Sequence(datasets.Value("float"   )   ),
                   "references": datasets.Sequence(datasets.Value("float"   )   ),
               }
           else:
               return {
                   "predictions": datasets.Value("float"   ),
                   "references": datasets.Value("float"   ),
               }







       def 				_a   (					self  ,UpperCAmelCase_  ,UpperCAmelCase_  ,UpperCAmelCase_=None  ,UpperCAmelCase_="uniform_average"  ,UpperCAmelCase_=True   )	->				Tuple:
           lowercase__									=    mean_squared_error(
               UpperCAmelCase_  ,UpperCAmelCase_  ,sample_weight=UpperCAmelCase_  ,multioutput=UpperCAmelCase_  ,squared=UpperCAmelCase_   )

           return {"mse": mse}




