
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__		(	__SCREAMING_SNAKE_CASE):
      _UpperCAmelCase				:    str           =			["""image_processor"""]
      _UpperCAmelCase				:    List[str]           =			"""SamImageProcessor"""
      def __init__(      self    ,  __magic_name__      ):
       super().__init__(__magic_name__      )
       lowerCamelCase		:	Optional[int]							=      self.image_processor
       lowerCamelCase		:	Tuple							=      -1_0
       lowerCamelCase		:	Tuple							=      self.image_processor.size["""longest_edge"""]
      def __call__(      self    ,  __magic_name__=None    ,  __magic_name__=None    ,  __magic_name__=None    ,  __magic_name__=None    ,  __magic_name__ = None    ,  **__magic_name__    ,  ):
       lowerCamelCase		:	int							=      self.image_processor(
           __magic_name__    ,  return_tensors=__magic_name__    ,  **__magic_name__    ,  )

       # pop arguments that are not used in the foward but used nevertheless
       lowerCamelCase		:	List[str]							=      encoding_image_processor["""original_sizes"""]

       if hasattr(__magic_name__    ,  """numpy"""      ):  # Checks if Torch or TF tensor
        lowerCamelCase		:	Optional[Any]							=      original_sizes.numpy()

       lowerCamelCase			,    lowerCamelCase			,    lowerCamelCase		:	Optional[Any]							=      self._check_and_preprocess_points(
           input_points=__magic_name__    ,  input_labels=__magic_name__    ,  input_boxes=__magic_name__    ,  )

       lowerCamelCase		:	str							=      self._normalize_and_convert(
           __magic_name__    ,  __magic_name__    ,  input_points=__magic_name__    ,  input_labels=__magic_name__    ,  input_boxes=__magic_name__    ,  return_tensors=__magic_name__    ,  )

       return encoding_image_processor
      def 						UpperCamelCase__							(      self    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__=None    ,  __magic_name__=None    ,  __magic_name__=None    ,  __magic_name__="pt"    ,  ):
       if input_points is not None:
        if len(__magic_name__      ) != len(__magic_name__      ):
         lowerCamelCase		:	Tuple							=      [
             self._normalize_coordinates(self.target_size    ,  __magic_name__    ,  original_sizes[0]      ) for point in input_points
         ]
        else:
         lowerCamelCase		:	Optional[int]							=      [
             self._normalize_coordinates(self.target_size    ,  __magic_name__    ,  __magic_name__      )
             for point, original_size in zip(__magic_name__    ,  __magic_name__      )
         ]
        # 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		:	Optional[int]							=      self._pad_points_and_labels(__magic_name__    ,  __magic_name__      )

        lowerCamelCase		:	Dict							=      np.array(__magic_name__      )

       if input_labels is not None:
        lowerCamelCase		:	Optional[int]							=      np.array(__magic_name__      )

       if input_boxes is not None:
        if len(__magic_name__      ) != len(__magic_name__      ):
         lowerCamelCase		:	List[Any]							=      [
             self._normalize_coordinates(self.target_size    ,  __magic_name__    ,  original_sizes[0]    ,  is_bounding_box=__magic_name__      )
             for box in input_boxes
         ]
        else:
         lowerCamelCase		:	List[str]							=      [
             self._normalize_coordinates(self.target_size    ,  __magic_name__    ,  __magic_name__    ,  is_bounding_box=__magic_name__      )
             for box, original_size in zip(__magic_name__    ,  __magic_name__      )
         ]
        lowerCamelCase		:	Dict							=      np.array(__magic_name__      )

       if input_boxes is not None:
        if return_tensors == "pt":
         lowerCamelCase		:	Optional[int]							=      torch.from_numpy(__magic_name__      )
         # boxes batch size of 1 by default
         lowerCamelCase		:	List[Any]							=      input_boxes.unsqueeze(1      ) if len(input_boxes.shape      ) != 3 else input_boxes
        elif return_tensors == "tf":
         lowerCamelCase		:	int							=      tf.convert_to_tensor(__magic_name__      )
         # boxes batch size of 1 by default
         lowerCamelCase		:	List[str]							=      tf.expand_dims(__magic_name__    ,  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		:	Tuple							=      torch.from_numpy(__magic_name__      )
         # point batch size of 1 by default
         lowerCamelCase		:	str							=      input_points.unsqueeze(1      ) if len(input_points.shape      ) != 4 else input_points
        elif return_tensors == "tf":
         lowerCamelCase		:	Any							=      tf.convert_to_tensor(__magic_name__      )
         # point batch size of 1 by default
         lowerCamelCase		:	int							=      tf.expand_dims(__magic_name__    ,  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		:	Tuple							=      torch.from_numpy(__magic_name__      )
         # point batch size of 1 by default
         lowerCamelCase		:	Union[str, Any]							=      input_labels.unsqueeze(1      ) if len(input_labels.shape      ) != 3 else input_labels
        elif return_tensors == "tf":
         lowerCamelCase		:	Any							=      tf.convert_to_tensor(__magic_name__      )
         # point batch size of 1 by default
         lowerCamelCase		:	Union[str, Any]							=      tf.expand_dims(__magic_name__    ,  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    ,  __magic_name__    ,  __magic_name__      ):
       lowerCamelCase		:	List[str]							=      max([point.shape[0] for point in input_points]      )
       lowerCamelCase		:	int							=      []
       for i, point in enumerate(__magic_name__      ):
        if point.shape[0] != expected_nb_points:
         lowerCamelCase		:	Dict							=      np.concatenate(
             [point, np.zeros((expected_nb_points - point.shape[0], 2)      ) + self.point_pad_value]    ,  axis=0      )
         lowerCamelCase		:	Tuple							=      np.append(input_labels[i]    ,  [self.point_pad_value]      )
        processed_input_points.append(__magic_name__      )
       lowerCamelCase		:	Union[str, Any]							=      processed_input_points
       return input_points, input_labels
      def 						UpperCamelCase__							(      self    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__=False      ):
       lowerCamelCase			,    lowerCamelCase		:	Optional[int]							=      original_size
       lowerCamelCase			,    lowerCamelCase		:	Union[str, Any]							=      self.image_processor._get_preprocess_shape(__magic_name__    ,  longest_edge=__magic_name__      )
       lowerCamelCase		:	List[Any]							=      deepcopy(__magic_name__      ).astype(__magic_name__      )

       if is_bounding_box:
        lowerCamelCase		:	Optional[Any]							=      coords.reshape(-1    ,  2    ,  2      )

       lowerCamelCase		:	Tuple							=      coords[..., 0] * (new_w / old_w)
       lowerCamelCase		:	Dict							=      coords[..., 1] * (new_h / old_h)

       if is_bounding_box:
        lowerCamelCase		:	Union[str, Any]							=      coords.reshape(-1    ,  4      )

       return coords
      def 						UpperCamelCase__							(      self    ,  __magic_name__=None    ,  __magic_name__=None    ,  __magic_name__=None    ,  ):
       if input_points is not None:
        if hasattr(__magic_name__    ,  """numpy"""      ):  # Checks for TF or Torch tensor
         lowerCamelCase		:	List[Any]							=      input_points.numpy().tolist()

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

       if input_labels is not None:
        if hasattr(__magic_name__    ,  """numpy"""      ):
         lowerCamelCase		:	int							=      input_labels.numpy().tolist()

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

       if input_boxes is not None:
        if hasattr(__magic_name__    ,  """numpy"""      ):
         lowerCamelCase		:	Union[str, Any]							=      input_boxes.numpy().tolist()

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

       return input_points, input_labels, input_boxes
      @property
      def 						UpperCamelCase__							(      self      ):
       lowerCamelCase		:	Optional[Any]							=      self.image_processor.model_input_names
       return list(dict.fromkeys(__magic_name__      )      )






      def 						UpperCamelCase__							(      self    ,  *__magic_name__    ,  **__magic_name__      ):
       return self.image_processor.post_process_masks(*__magic_name__    ,  **__magic_name__      )






from scipy.stats import pearsonr

import datasets


_lowerCamelCase					   ="""
Pearson correlation coefficient and p-value for testing non-correlation.
The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.
The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.
"""


_lowerCamelCase					   ="""
Args:
    predictions (`list` of `int`): Predicted class labels, as returned by a model.
    references (`list` of `int`): Ground truth labels.
    return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.

Returns:
    pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.
    p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.

Examples:

    Example 1-A simple example using only predictions and references.
        >>> pearsonr_metric = datasets.load_metric(\"pearsonr\")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])
        >>> print(round(results['pearsonr'], 2))
        -0.74

    Example 2-The same as Example 1, but that also returns the `p-value`.
        >>> pearsonr_metric = datasets.load_metric(\"pearsonr\")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)
        >>> print(sorted(list(results.keys())))
        ['p-value', 'pearsonr']
        >>> print(round(results['pearsonr'], 2))
        -0.74
        >>> print(round(results['p-value'], 2))
        0.15
"""


_lowerCamelCase					   ="""
@article{2020SciPy-NMeth,
author  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
      Haberland, Matt and Reddy, Tyler and Cournapeau, David and
      Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
      Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
      Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
      Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
      Kern, Robert and Larson, Eric and Carey, C J and
      Polat, Ilhan and Feng, Yu and Moore, Eric W. and
      {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
      Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
      Harris, Charles R. and Archibald, Anne M. and
      Ribeiro, Antonio H. and Pedregosa, Fabian and
      {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
title   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
      Computing in Python}},
journal = {Nature Methods},
year    = {2020},
volume  = {17},
pages   = {261--272},
adsurl  = {https://rdcu.be/b08Wh},
doi = {10.1038/s41592-019-0686-2},
}
"""





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION  ,   _KWARGS_DESCRIPTION)
class 							A__		(	datasets.Metric):
      def 						UpperCamelCase__							(      self      ):
       return datasets.MetricInfo(
           description=_DESCRIPTION    ,  citation=_CITATION    ,  inputs_description=_KWARGS_DESCRIPTION    ,  features=datasets.Features(
               {
                   """predictions""": datasets.Value("""float"""      ),
                   """references""": datasets.Value("""float"""      ),
               }      )    ,  reference_urls=["""https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html"""]    ,  )






      def 						UpperCamelCase__							(      self    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__=False      ):
       if return_pvalue:
        lowerCamelCase		:	Optional[Any]							=      pearsonr(__magic_name__    ,  __magic_name__      )
        return {"pearsonr": results[0], "p-value": results[1]}
       else:
        return {"pearsonr": float(pearsonr(__magic_name__    ,  __magic_name__      )[0]      )}




