

import math
from typing import Dict, Iterable, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    is_torch_available,
    is_torch_tensor,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_torch_available():
 import torch

if is_vision_available():
 import PIL


lowerCAmelCase__      		=			logging.get_logger(__name__)


def 	_A  (					A__  ,       A__  ,       A__  ,       A__   ):






 """simple docstring"""



 def constraint_to_multiple_of(A__  ,       A__  ,       A__=0  ,       A__=None   ):
  __lowercase													=				round(val / multiple   ) * multiple

  if max_val is not None and x > max_val:
   __lowercase													=				math.floor(val / multiple   ) * multiple

  if x < min_val:
   __lowercase													=				math.ceil(val / multiple   ) * multiple

  return x

 __lowercase													=				(output_size, output_size) if isinstance(A__  ,       A__   ) else output_size

 __lowercase													=				get_image_size(A__   )
 __lowercase													=				output_size

 # determine new height and width
 __lowercase													=				output_height / input_height
 __lowercase													=				output_width / input_width

 if keep_aspect_ratio:
  # scale as little as possible
  if abs(1 - scale_width   ) < abs(1 - scale_height   ):
   # fit width
   __lowercase													=				scale_width
  else:
   # fit height
   __lowercase													=				scale_height

 __lowercase													=				constraint_to_multiple_of(scale_height * input_height  ,       multiple=A__   )
 __lowercase													=				constraint_to_multiple_of(scale_width * input_width  ,       multiple=A__   )

 return (new_height, new_width)






class     lowercase_			(_snake_case   ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE					:						Any           =    ["""pixel_values"""]






  def __init__(   self     :  List[str]      ,lowercase__     :  List[Any] = True      ,lowercase__     :  Any = None      ,lowercase__     :  List[Any] = PILImageResampling.BILINEAR      ,lowercase__     :  str = False      ,lowercase__     :  Tuple = 1      ,lowercase__     :  int = True      ,lowercase__     :  Dict = 1 / 2_5_5      ,lowercase__     :  Tuple = True      ,lowercase__     :  str = None      ,lowercase__     :  List[str] = None      ,**lowercase__     :  List[str]      ,):
   super().__init__(**snake_case_    )
   __lowercase													=				size if size is not None else {"height": 3_8_4, "width": 3_8_4}
   __lowercase													=				get_size_dict(snake_case_    )
   __lowercase													=				do_resize
   __lowercase													=				size
   __lowercase													=				keep_aspect_ratio
   __lowercase													=				ensure_multiple_of
   __lowercase													=				resample
   __lowercase													=				do_rescale
   __lowercase													=				rescale_factor
   __lowercase													=				do_normalize
   __lowercase													=				image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
   __lowercase													=				image_std if image_std is not None else IMAGENET_STANDARD_STD






  def       SCREAMING_SNAKE_CASE   (   self     :  Dict      ,lowercase__     :  int      ,lowercase__     :  List[str]      ,lowercase__     :  Dict = False      ,lowercase__     :  Tuple = 1      ,lowercase__     :  List[Any] = PILImageResampling.BICUBIC      ,lowercase__     :  Union[str, Any] = None      ,**lowercase__     :  Optional[Any]      ,):
   __lowercase													=				get_size_dict(snake_case_    )
   if "height" not in size or "width" not in size:
    raise ValueError(F"The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}"    )
   __lowercase													=				get_resize_output_image_size(
       snake_case_      ,output_size=(size['''height'''], size['''width'''])      ,keep_aspect_ratio=snake_case_      ,multiple=snake_case_      ,)
   return resize(snake_case_      ,size=snake_case_      ,resample=snake_case_      ,data_format=snake_case_      ,**snake_case_    )






  def       SCREAMING_SNAKE_CASE   (   self     :  Optional[Any]      ,lowercase__     :  Dict      ,lowercase__     :  str      ,lowercase__     :  Tuple = None      ,**lowercase__     :  Any      ,):
   return rescale(snake_case_      ,scale=snake_case_      ,data_format=snake_case_      ,**snake_case_    )






  def       SCREAMING_SNAKE_CASE   (   self     :  Union[str, Any]      ,lowercase__     :  Optional[Any]      ,lowercase__     :  Optional[Any]      ,lowercase__     :  Dict      ,lowercase__     :  Dict = None      ,**lowercase__     :  List[str]      ,):
   return normalize(snake_case_      ,mean=snake_case_      ,std=snake_case_      ,data_format=snake_case_      ,**snake_case_    )






  def       SCREAMING_SNAKE_CASE   (   self     :  Tuple      ,lowercase__     :  List[Any]      ,lowercase__     :  List[Any] = None      ,lowercase__     :  Union[str, Any] = None      ,lowercase__     :  List[str] = None      ,lowercase__     :  List[str] = None      ,lowercase__     :  Optional[Any] = None      ,lowercase__     :  Dict = None      ,lowercase__     :  Union[str, Any] = None      ,lowercase__     :  List[Any] = None      ,lowercase__     :  Any = None      ,lowercase__     :  Optional[int] = None      ,lowercase__     :  Dict = None      ,lowercase__     :  Dict = ChannelDimension.FIRST      ,**lowercase__     :  List[str]      ,):
   __lowercase													=				do_resize if do_resize is not None else self.do_resize
   __lowercase													=				size if size is not None else self.size
   __lowercase													=				get_size_dict(snake_case_    )
   __lowercase													=				keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
   __lowercase													=				ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
   __lowercase													=				resample if resample is not None else self.resample
   __lowercase													=				do_rescale if do_rescale is not None else self.do_rescale
   __lowercase													=				rescale_factor if rescale_factor is not None else self.rescale_factor
   __lowercase													=				do_normalize if do_normalize is not None else self.do_normalize
   __lowercase													=				image_mean if image_mean is not None else self.image_mean
   __lowercase													=				image_std if image_std is not None else self.image_std

   __lowercase													=				make_list_of_images(snake_case_    )

   if not valid_images(snake_case_    ):
    raise ValueError(
        '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
        '''torch.Tensor, tf.Tensor or jax.ndarray.'''    )

   if do_resize and size is None or resample is None:
    raise ValueError('''Size and resample must be specified if do_resize is True.'''    )

   if do_rescale and rescale_factor is None:
    raise ValueError('''Rescale factor must be specified if do_rescale is True.'''    )

   if do_normalize and (image_mean is None or image_std is None):
    raise ValueError('''Image mean and std must be specified if do_normalize is True.'''    )

   # All transformations expect numpy arrays.
   __lowercase													=				[to_numpy_array(snake_case_    ) for image in images]

   if do_resize:
    __lowercase													=				[self.resize(image=snake_case_      ,size=snake_case_      ,resample=snake_case_    ) for image in images]

   if do_rescale:
    __lowercase													=				[self.rescale(image=snake_case_      ,scale=snake_case_    ) for image in images]

   if do_normalize:
    __lowercase													=				[self.normalize(image=snake_case_      ,mean=snake_case_      ,std=snake_case_    ) for image in images]

   __lowercase													=				[to_channel_dimension_format(snake_case_      ,snake_case_    ) for image in images]

   __lowercase													=				{"pixel_values": images}
   return BatchFeature(data=snake_case_      ,tensor_type=snake_case_    )






  def       SCREAMING_SNAKE_CASE   (   self     :  int      ,lowercase__     :  List[Any]      ,lowercase__     :  Tuple = None    ):
   __lowercase													=				outputs.logits

   # Resize logits and compute semantic segmentation maps
   if target_sizes is not None:
    if len(snake_case_    ) != len(snake_case_    ):
     raise ValueError(
         '''Make sure that you pass in as many target sizes as the batch dimension of the logits'''    )

    if is_torch_tensor(snake_case_    ):
     __lowercase													=				target_sizes.numpy()

    __lowercase													=				[]

    for idx in range(len(snake_case_    )    ):
     __lowercase													=				torch.nn.functional.interpolate(
         logits[idx].unsqueeze(dim=0    )      ,size=target_sizes[idx]      ,mode='''bilinear'''      ,align_corners=snake_case_    )
     __lowercase													=				resized_logits[0].argmax(dim=0    )
     semantic_segmentation.append(snake_case_    )
   else:
    __lowercase													=				logits.argmax(dim=1    )
    __lowercase													=				[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]    )]

   return semantic_segmentation




'''simple docstring'''






from scipy.stats import spearmanr

import datasets


lowerCAmelCase__      		=			'''
The Spearman rank-order correlation coefficient is a measure of the
relationship between two datasets. Like other correlation coefficients,
this one varies between -1 and +1 with 0 implying no correlation.
Positive correlations imply that as data in dataset x increases, so
does data in dataset y. Negative correlations imply that as x increases,
y decreases. Correlations of -1 or +1 imply an exact monotonic relationship.

Unlike the Pearson correlation, the Spearman correlation does not
assume that both datasets are normally distributed.

The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Spearman correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.
'''

lowerCAmelCase__      		=			'''
Args:
    predictions (`List[float]`): Predicted labels, as returned by a model.
    references (`List[float]`): Ground truth labels.
    return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns
            only the spearmanr score. Defaults to `False`.
Returns:
    spearmanr (`float`): Spearman correlation coefficient.
    p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.
Examples:
    Example 1:
        >>> spearmanr_metric = datasets.load_metric("spearmanr")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])
        >>> print(results)
        {\'spearmanr\': -0.7}

    Example 2:
        >>> spearmanr_metric = datasets.load_metric("spearmanr")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],
        ...                                     predictions=[10, 9, 2.5, 6, 4],
        ...                                     return_pvalue=True)
        >>> print(results[\'spearmanr\'])
        -0.7
        >>> print(round(results[\'spearmanr_pvalue\'], 2))
        0.19
'''

lowerCAmelCase__      		=			R'''\
@book{kokoska2000crc,
  title={CRC standard probability and statistics tables and formulae},
  author={Kokoska, Stephen and Zwillinger, Daniel},
  year={2000},
  publisher={Crc Press}
}
@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, {\.I}lhan 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, Ant{\^o}nio 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     lowercase_			(datasets.Metric   ):




  """simple docstring"""




  def       SCREAMING_SNAKE_CASE   (   self     :  Optional[int]    ):
   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.spearmanr.html''']      ,)






  def       SCREAMING_SNAKE_CASE   (   self     :  Tuple      ,lowercase__     :  List[Any]      ,lowercase__     :  List[Any]      ,lowercase__     :  Union[str, Any]=False    ):
   __lowercase													=				spearmanr(lowercase__      ,lowercase__    )
   if return_pvalue:
    return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
   else:
    return {"spearmanr": results[0]}

