


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


__UpperCAmelCase    :Tuple				       =     logging.get_logger(__name__)




def 			_a			(		_lowercase      :			Dict    ,      _lowercase      :			Dict    ,      _lowercase      :			List[Any]    ,      _lowercase      :			Dict						):





     '''simple docstring'''






     def constraint_to_multiple_of(_lowercase      :			int    ,      _lowercase      :			Dict    ,      _lowercase      :			Any=0    ,      _lowercase      :			Tuple=None						):
          __UpperCAmelCase			:				Union[str, Any]													=    round(val / multiple						) * multiple

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

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

          return x

     __UpperCAmelCase			:				Any													=    (output_size, output_size) if isinstance(_lowercase    ,      _lowercase						) else output_size

     __UpperCAmelCase							,     __UpperCAmelCase			:				Any													=    get_image_size(_lowercase						)
     __UpperCAmelCase							,     __UpperCAmelCase			:				Tuple													=    output_size

     # determine new height and width
     __UpperCAmelCase			:				Any													=    output_height / input_height
     __UpperCAmelCase			:				Optional[Any]													=    output_width / input_width

     if keep_aspect_ratio:
          # scale as little as possible
          if abs(1 - scale_width						) < abs(1 - scale_height						):
               # fit width
               __UpperCAmelCase			:				Optional[Any]													=    scale_width
          else:
               # fit height
               __UpperCAmelCase			:				Optional[Any]													=    scale_height

     __UpperCAmelCase			:				Optional[int]													=    constraint_to_multiple_of(scale_height * input_height    ,      multiple=_lowercase						)
     __UpperCAmelCase			:				Union[str, Any]													=    constraint_to_multiple_of(scale_width * input_width    ,      multiple=_lowercase						)

     return (new_height, new_width)



class 			a       (	_a ):


     """simple docstring"""






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

     def __init__(       self  :	int							,				snake_case  :	bool = True							,				snake_case  :	Dict[str, int] = None							,				snake_case  :	PILImageResampling = PILImageResampling.BILINEAR							,				snake_case  :	bool = False							,				snake_case  :	int = 1							,				snake_case  :	bool = True							,				snake_case  :	Union[int, float] = 1 / 255							,				snake_case  :	bool = True							,				snake_case  :	Optional[Union[float, List[float]]] = None							,				snake_case  :	Optional[Union[float, List[float]]] = None							,				**snake_case  :	Optional[int]							,				)		->							None:
          super().__init__(**__A    )
          __UpperCAmelCase			:				int													=    size if size is not None else {'''height''': 384, '''width''': 384}
          __UpperCAmelCase			:				int													=    get_size_dict(__A    )
          __UpperCAmelCase			:				Any													=    do_resize
          __UpperCAmelCase			:				Union[str, Any]													=    size
          __UpperCAmelCase			:				Union[str, Any]													=    keep_aspect_ratio
          __UpperCAmelCase			:				Union[str, Any]													=    ensure_multiple_of
          __UpperCAmelCase			:				Any													=    resample
          __UpperCAmelCase			:				str													=    do_rescale
          __UpperCAmelCase			:				Tuple													=    rescale_factor
          __UpperCAmelCase			:				List[str]													=    do_normalize
          __UpperCAmelCase			:				Any													=    image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
          __UpperCAmelCase			:				int													=    image_std if image_std is not None else IMAGENET_STANDARD_STD

     def 				lowerCamelCase__				(       self  :	Dict							,				snake_case  :	np.ndarray							,				snake_case  :	Dict[str, int]							,				snake_case  :	bool = False							,				snake_case  :	int = 1							,				snake_case  :	PILImageResampling = PILImageResampling.BICUBIC							,				snake_case  :	Optional[Union[str, ChannelDimension]] = None							,				**snake_case  :	Union[str, Any]							,				)		->							np.ndarray:
          __UpperCAmelCase			:				List[Any]													=    get_size_dict(__A    )
          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()}'    )
          __UpperCAmelCase			:				str													=    get_resize_output_image_size(
              __A							,				output_size=(size['''height'''], size['''width'''])							,				keep_aspect_ratio=__A							,				multiple=__A							,				)
          return resize(__A							,				size=__A							,				resample=__A							,				data_format=__A							,				**__A    )

     def 				lowerCamelCase__				(       self  :	Optional[int]							,				snake_case  :	np.ndarray							,				snake_case  :	Union[int, float]							,				snake_case  :	Optional[Union[str, ChannelDimension]] = None							,				**snake_case  :	List[str]							,				)		->							Optional[int]:
          return rescale(__A							,				scale=__A							,				data_format=__A							,				**__A    )

     def 				lowerCamelCase__				(       self  :	Optional[int]							,				snake_case  :	np.ndarray							,				snake_case  :	Union[float, List[float]]							,				snake_case  :	Union[float, List[float]]							,				snake_case  :	Optional[Union[str, ChannelDimension]] = None							,				**snake_case  :	Optional[Any]							,				)		->							np.ndarray:
          return normalize(__A							,				mean=__A							,				std=__A							,				data_format=__A							,				**__A    )

     def 				lowerCamelCase__				(       self  :	Any							,				snake_case  :	ImageInput							,				snake_case  :	bool = None							,				snake_case  :	int = None							,				snake_case  :	bool = None							,				snake_case  :	int = None							,				snake_case  :	PILImageResampling = None							,				snake_case  :	bool = None							,				snake_case  :	float = None							,				snake_case  :	bool = None							,				snake_case  :	Optional[Union[float, List[float]]] = None							,				snake_case  :	Optional[Union[float, List[float]]] = None							,				snake_case  :	Optional[Union[str, TensorType]] = None							,				snake_case  :	ChannelDimension = ChannelDimension.FIRST							,				**snake_case  :	Tuple							,				)		->							PIL.Image.Image:
          __UpperCAmelCase			:				List[str]													=    do_resize if do_resize is not None else self.do_resize
          __UpperCAmelCase			:				Union[str, Any]													=    size if size is not None else self.size
          __UpperCAmelCase			:				List[str]													=    get_size_dict(__A    )
          __UpperCAmelCase			:				Tuple													=    keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
          __UpperCAmelCase			:				Optional[Any]													=    ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
          __UpperCAmelCase			:				Tuple													=    resample if resample is not None else self.resample
          __UpperCAmelCase			:				Any													=    do_rescale if do_rescale is not None else self.do_rescale
          __UpperCAmelCase			:				Optional[Any]													=    rescale_factor if rescale_factor is not None else self.rescale_factor
          __UpperCAmelCase			:				Union[str, Any]													=    do_normalize if do_normalize is not None else self.do_normalize
          __UpperCAmelCase			:				Dict													=    image_mean if image_mean is not None else self.image_mean
          __UpperCAmelCase			:				Optional[int]													=    image_std if image_std is not None else self.image_std

          __UpperCAmelCase			:				str													=    make_list_of_images(__A    )

          if not valid_images(__A    ):
               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.
          __UpperCAmelCase			:				List[Any]													=    [to_numpy_array(__A    ) for image in images]

          if do_resize:
               __UpperCAmelCase			:				Dict													=    [self.resize(image=__A							,				size=__A							,				resample=__A    ) for image in images]

          if do_rescale:
               __UpperCAmelCase			:				List[Any]													=    [self.rescale(image=__A							,				scale=__A    ) for image in images]

          if do_normalize:
               __UpperCAmelCase			:				Dict													=    [self.normalize(image=__A							,				mean=__A							,				std=__A    ) for image in images]

          __UpperCAmelCase			:				Dict													=    [to_channel_dimension_format(__A							,				__A    ) for image in images]

          __UpperCAmelCase			:				List[Any]													=    {'''pixel_values''': images}
          return BatchFeature(data=__A							,				tensor_type=__A    )






     def 				lowerCamelCase__				(       self  :	Union[str, Any]							,				snake_case  :	int							,				snake_case  :	List[Tuple] = None    )		->							str:
          __UpperCAmelCase			:				Optional[Any]													=    outputs.logits

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

               if is_torch_tensor(__A    ):
                    __UpperCAmelCase			:				Optional[Any]													=    target_sizes.numpy()

               __UpperCAmelCase			:				Optional[Any]													=    []

               for idx in range(len(__A    )    ):
                    __UpperCAmelCase			:				Optional[int]													=    torch.nn.functional.interpolate(
                        logits[idx].unsqueeze(dim=0    )							,				size=target_sizes[idx]							,				mode='''bilinear'''							,				align_corners=__A    )
                    __UpperCAmelCase			:				List[str]													=    resized_logits[0].argmax(dim=0    )
                    semantic_segmentation.append(__A    )
          else:
               __UpperCAmelCase			:				Union[str, Any]													=    logits.argmax(dim=1    )
               __UpperCAmelCase			:				Dict													=    [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]    )]

          return semantic_segmentation



'''simple docstring'''



from scipy.stats import pearsonr

import datasets


__UpperCAmelCase    :Tuple				       =     "\nPearson correlation coefficient and p-value for testing non-correlation.\nThe 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.\nThe 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.\n"


__UpperCAmelCase    :List[str]				       =     "\nArgs:\n    predictions (`list` of `int`): Predicted class labels, as returned by a model.\n    references (`list` of `int`): Ground truth labels.\n    return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n    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.\n    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.\n\nExamples:\n\n    Example 1-A simple example using only predictions and references.\n        >>> pearsonr_metric = datasets.load_metric(\"pearsonr\")\n        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n        >>> print(round(results['pearsonr'], 2))\n        -0.74\n\n    Example 2-The same as Example 1, but that also returns the `p-value`.\n        >>> pearsonr_metric = datasets.load_metric(\"pearsonr\")\n        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n        >>> print(sorted(list(results.keys())))\n        ['p-value', 'pearsonr']\n        >>> print(round(results['pearsonr'], 2))\n        -0.74\n        >>> print(round(results['p-value'], 2))\n        0.15\n"


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



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


     """simple docstring"""






     def 				lowerCamelCase__				(       self  :	List[Any]    )		->							Union[str, Any]:
          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 				lowerCamelCase__				(       self  :	Any							,				snake_case  :	Union[str, Any]							,				snake_case  :	int							,				snake_case  :	Dict=False    )		->							List[Any]:
          if return_pvalue:
               __UpperCAmelCase			:				Tuple													=    pearsonr(snake_case							,				snake_case    )
               return {"pearsonr": results[0], "p-value": results[1]}
          else:
               return {"pearsonr": float(pearsonr(snake_case							,				snake_case    )[0]    )}