


'''simple docstring'''







import warnings
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

from .configuration_utils import ConfigMixin, register_to_config
from .utils import CONFIG_NAME, PIL_INTERPOLATION, deprecate







class A__	(						UpperCAmelCase__				):
      __UpperCamelCase	:  Tuple     	=							CONFIG_NAME






      @register_to_config
      def __init__(			self      :List[Any]					,						SCREAMING_SNAKE_CASE      :int = True					,						SCREAMING_SNAKE_CASE      :int = 8					,						SCREAMING_SNAKE_CASE      :Optional[int] = "lanczos"					,						SCREAMING_SNAKE_CASE      :List[Any] = True					,						SCREAMING_SNAKE_CASE      :int = False					,						)	-> str:




             '''simple docstring'''
             super().__init__()






      @staticmethod
      def __UpperCAmelCase	(			SCREAMING_SNAKE_CASE      :int     )	-> Optional[int]:




             '''simple docstring'''





             if images.ndim == 3:
                    _a   :			List[Any]					 =images[None, ...]
             _a   :			List[Any]					 =(images * 2_5_5).round().astype("""uint8"""     )
             if images.shape[-1] == 1:
                    # special case for grayscale (single channel) images
                    _a   :			str					 =[Image.fromarray(image.squeeze()					,						mode="""L"""     ) for image in images]
             else:
                    _a   :			Optional[Any]					 =[Image.fromarray(__A     ) for image in images]

             return pil_images






      @staticmethod
      def __UpperCAmelCase	(			SCREAMING_SNAKE_CASE      :Union[str, Any]     )	-> Optional[int]:




             '''simple docstring'''





             if not isinstance(__A					,						__A     ):
                    _a   :			Any					 =[images]
             _a   :			List[Any]					 =[np.array(__A     ).astype(np.floataa     ) / 255.0 for image in images]
             _a   :			Any					 =np.stack(__A					,						axis=0     )

             return images






      @staticmethod
      def __UpperCAmelCase	(			SCREAMING_SNAKE_CASE      :Optional[Any]     )	-> str:




             '''simple docstring'''





             if images.ndim == 3:
                    _a   :			Union[str, Any]					 =images[..., None]

             _a   :			List[str]					 =torch.from_numpy(images.transpose(0					,						3					,						1					,						2     )     )
             return images






      @staticmethod
      def __UpperCAmelCase	(			SCREAMING_SNAKE_CASE      :List[str]     )	-> List[str]:




             '''simple docstring'''
             _a   :			Union[str, Any]					 =images.cpu().permute(0					,						2					,						3					,						1     ).float().numpy()
             return images






      @staticmethod
      def __UpperCAmelCase	(			SCREAMING_SNAKE_CASE      :str     )	-> Optional[Any]:




             '''simple docstring'''
             return 2.0 * images - 1.0






      @staticmethod
      def __UpperCAmelCase	(			SCREAMING_SNAKE_CASE      :Any     )	-> List[Any]:




             '''simple docstring'''
             return (images / 2 + 0.5).clamp(0					,						1     )






      @staticmethod
      def __UpperCAmelCase	(			SCREAMING_SNAKE_CASE      :str     )	-> Any:




             '''simple docstring'''
             _a   :			List[Any]					 =image.convert("""RGB"""     )
             return image






      def __UpperCAmelCase	(			self      :Union[str, Any]					,						SCREAMING_SNAKE_CASE      :int					,						SCREAMING_SNAKE_CASE      :Tuple = None					,						SCREAMING_SNAKE_CASE      :Union[str, Any] = None					,						)	-> int:




             '''simple docstring'''





             if height is None:
                    _a   :			Dict					 =image.height
             if width is None:
                    _a   :			Union[str, Any]					 =image.width

             _a   :			int					 =(
                 x - x % self.config.vae_scale_factor for x in (width, height)
             )  # resize to integer multiple of vae_scale_factor
             _a   :			int					 =image.resize((width, height)					,						resample=PIL_INTERPOLATION[self.config.resample]     )
             return image






      def __UpperCAmelCase	(			self      :Optional[int]					,						SCREAMING_SNAKE_CASE      :List[str]					,						SCREAMING_SNAKE_CASE      :Tuple = None					,						SCREAMING_SNAKE_CASE      :Union[str, Any] = None					,						)	-> int:




             '''simple docstring'''
             _a   :			Any					 =(PIL.Image.Image, np.ndarray, torch.Tensor)
             if isinstance(__A					,						__A     ):
                    _a   :			List[str]					 =[image]
             elif not (isinstance(__A					,						__A     ) and all(isinstance(__A					,						__A     ) for i in image     )):
                    raise ValueError(
                        f"Input is in incorrect format: {[type(__A     ) for i in image]}. Currently, we only support {', '.join(__A     )}"     )

             if isinstance(image[0]					,						PIL.Image.Image     ):
                    if self.config.do_convert_rgb:
                           _a   :			Union[str, Any]					 =[self.convert_to_rgb(__A     ) for i in image]
                    if self.config.do_resize:
                           _a   :			List[Any]					 =[self.resize(__A					,						__A					,						__A     ) for i in image]
                    _a   :			Tuple					 =self.pil_to_numpy(__A     )  # to np
                    _a   :			List[Any]					 =self.numpy_to_pt(__A     )  # to pt

             elif isinstance(image[0]					,						np.ndarray     ):
                    _a   :			int					 =np.concatenate(__A					,						axis=0     ) if image[0].ndim == 4 else np.stack(__A					,						axis=0     )
                    _a   :			Tuple					 =self.numpy_to_pt(__A     )
                    _a   :			Dict					 =image.shape
                    if self.config.do_resize and (
                        height % self.config.vae_scale_factor != 0 or width % self.config.vae_scale_factor != 0
                    ):
                           raise ValueError(
                               f"Currently we only support resizing for PIL image - please resize your numpy array to be divisible by {self.config.vae_scale_factor}"
                               f"currently the sizes are {height} and {width}. You can also pass a PIL image instead to use resize option in VAEImageProcessor"     )

             elif isinstance(image[0]					,						torch.Tensor     ):
                    _a   :			str					 =torch.cat(__A					,						axis=0     ) if image[0].ndim == 4 else torch.stack(__A					,						axis=0     )
                    _a   :			Any					 =image.shape

                    # don't need any preprocess if the image is latents
                    if channel == 4:
                           return image

                    if self.config.do_resize and (
                        height % self.config.vae_scale_factor != 0 or width % self.config.vae_scale_factor != 0
                    ):
                           raise ValueError(
                               f"Currently we only support resizing for PIL image - please resize your pytorch tensor to be divisible by {self.config.vae_scale_factor}"
                               f"currently the sizes are {height} and {width}. You can also pass a PIL image instead to use resize option in VAEImageProcessor"     )

                     # expected range [0,1], normalize to [-1,1]
             _a   :			Any					 =self.config.do_normalize
             if image.min() < 0:
                    warnings.warn(
                        """Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] """
                        f"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{image.min()},{image.max()}]"					,						__A					,						)
                    _a   :			List[Any]					 =False

             if do_normalize:
                    _a   :			Dict					 =self.normalize(__A     )

             return image






      def __UpperCAmelCase	(			self      :str					,						SCREAMING_SNAKE_CASE      :List[str]					,						SCREAMING_SNAKE_CASE      :List[Any] = "pil"					,						SCREAMING_SNAKE_CASE      :Any = None					,						)	-> int:




             '''simple docstring'''





             if not isinstance(__A					,						torch.Tensor     ):
                    raise ValueError(
                        f"Input for postprocessing is in incorrect format: {type(__A     )}. We only support pytorch tensor"     )
             if output_type not in ["latent", "pt", "np", "pil"]:
                    _a   :			List[str]					 =(
                        f"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
                        "`pil`, `np`, `pt`, `latent`"
                    )
                    deprecate("""Unsupported output_type"""					,						"""1.0.0"""					,						__A					,						standard_warn=__A     )
                    _a   :			Any					 ="np"

             if output_type == "latent":
                    return image

             if do_denormalize is None:
                    _a   :			Optional[int]					 =[self.config.do_normalize] * image.shape[0]

             _a   :			str					 =torch.stack(
                 [self.denormalize(image[i]     ) if do_denormalize[i] else image[i] for i in range(image.shape[0]     )]     )

             if output_type == "pt":
                    return image

             _a   :			int					 =self.pt_to_numpy(__A     )

             if output_type == "np":
                    return image

             if output_type == "pil":
                    return self.numpy_to_pil(__A     )







class A__	(						UpperCAmelCase__				):
      __UpperCamelCase	:  Dict     	=							CONFIG_NAME






      @register_to_config
      def __init__(			self      :List[Any]					,						SCREAMING_SNAKE_CASE      :Tuple = True					,						SCREAMING_SNAKE_CASE      :List[Any] = 8					,						SCREAMING_SNAKE_CASE      :Union[str, Any] = "lanczos"					,						SCREAMING_SNAKE_CASE      :List[Any] = True					,						)	-> Dict:




             '''simple docstring'''
             super().__init__()






      @staticmethod
      def __UpperCAmelCase	(			SCREAMING_SNAKE_CASE      :str     )	-> Optional[Any]:




             '''simple docstring'''





             if images.ndim == 3:
                    _a   :			List[str]					 =images[None, ...]
             _a   :			Tuple					 =(images * 2_5_5).round().astype("""uint8"""     )
             if images.shape[-1] == 1:
                    # special case for grayscale (single channel) images
                    _a   :			List[Any]					 =[Image.fromarray(image.squeeze()					,						mode="""L"""     ) for image in images]
             else:
                    _a   :			Any					 =[Image.fromarray(image[:, :, :3]     ) for image in images]

             return pil_images






      @staticmethod
      def __UpperCAmelCase	(			SCREAMING_SNAKE_CASE      :List[Any]     )	-> str:




             '''simple docstring'''
             return image[:, :, 1] * 2**8 + image[:, :, 2]






      def __UpperCAmelCase	(			self      :Dict					,						SCREAMING_SNAKE_CASE      :int     )	-> Optional[Any]:




             '''simple docstring'''





             if images.ndim == 3:
                    _a   :			Union[str, Any]					 =images[None, ...]
             _a   :			int					 =images[:, :, :, 3:]
             if images.shape[-1] == 6:
                    _a   :			List[str]					 =(images_depth * 2_5_5).round().astype("""uint8"""     )
                    _a   :			Optional[int]					 =[
                        Image.fromarray(self.rgblike_to_depthmap(__A     )					,						mode="""I;16"""     ) for image_depth in images_depth
                    ]
             elif images.shape[-1] == 4:
                    _a   :			Tuple					 =(images_depth * 65_535.0).astype(np.uintaa     )
                    _a   :			int					 =[Image.fromarray(__A					,						mode="""I;16"""     ) for image_depth in images_depth]
             else:
                    raise Exception("""Not supported"""     )

             return pil_images






      def __UpperCAmelCase	(			self      :str					,						SCREAMING_SNAKE_CASE      :Dict					,						SCREAMING_SNAKE_CASE      :Tuple = "pil"					,						SCREAMING_SNAKE_CASE      :List[str] = None					,						)	-> Dict:




             '''simple docstring'''





             if not isinstance(__A					,						torch.Tensor     ):
                    raise ValueError(
                        f"Input for postprocessing is in incorrect format: {type(__A     )}. We only support pytorch tensor"     )
             if output_type not in ["latent", "pt", "np", "pil"]:
                    _a   :			Optional[Any]					 =(
                        f"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
                        "`pil`, `np`, `pt`, `latent`"
                    )
                    deprecate("""Unsupported output_type"""					,						"""1.0.0"""					,						__A					,						standard_warn=__A     )
                    _a   :			str					 ="np"

             if do_denormalize is None:
                    _a   :			Optional[Any]					 =[self.config.do_normalize] * image.shape[0]

             _a   :			Dict					 =torch.stack(
                 [self.denormalize(image[i]     ) if do_denormalize[i] else image[i] for i in range(image.shape[0]     )]     )

             _a   :			int					 =self.pt_to_numpy(__A     )

             if output_type == "np":
                    if image.shape[-1] == 6:
                           _a   :			Optional[Any]					 =np.stack([self.rgblike_to_depthmap(im[:, :, 3:]     ) for im in image]					,						axis=0     )
                    else:
                           _a   :			Union[str, Any]					 =image[:, :, :, 3:]
                    return image[:, :, :, :3], image_depth

             if output_type == "pil":
                    return self.numpy_to_pil(__A     ), self.numpy_to_depth(__A     )
             else:
                    raise Exception(f"This type {output_type} is not supported"     )









'''simple docstring'''







from sklearn.metrics import mean_absolute_error

import datasets


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

A__:   Union[str, Any]    =	'''\
Mean Absolute Error (MAE) is the mean of the magnitude of difference between the predicted and actual
values.
'''


A__:   str    =	'''
Args:
    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Estimated target values.
    references: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Ground truth (correct) target values.
    sample_weight: array-like of shape (n_samples,), default=None
        Sample weights.
    multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average"
        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.

                 "raw_values" : Returns a full set of errors in case of multioutput input.

                 "uniform_average" : Errors of all outputs are averaged with uniform weight.

Returns:
    mae : mean absolute error.
        If multioutput is "raw_values", then mean absolute error is returned for each output separately. If multioutput is "uniform_average" or an ndarray of weights, then the weighted average of all output errors is returned.
        MAE output is non-negative floating point. The best value is 0.0.
Examples:

    >>> mae_metric = datasets.load_metric("mae")
    >>> predictions = [2.5, 0.0, 2, 8]
    >>> references = [3, -0.5, 2, 7]
    >>> results = mae_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'mae\': 0.5}

    If you\'re using multi-dimensional lists, then set the config as follows :

    >>> mae_metric = datasets.load_metric("mae", "multilist")
    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]
    >>> references = [[0, 2], [-1, 2], [8, -5]]
    >>> results = mae_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'mae\': 0.75}
    >>> results = mae_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\')
    >>> print(results)
    {\'mae\': array([0.5, 1. ])}
'''







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






      def __UpperCAmelCase	(			self      :List[Any]     )	-> Dict:




             '''simple docstring'''
             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_absolute_error.html"""
                 ]					,						)






      def __UpperCAmelCase	(			self      :Dict     )	-> List[str]:




             '''simple docstring'''
             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 __UpperCAmelCase	(			self      :Any					,						SCREAMING_SNAKE_CASE      :Union[str, Any]					,						SCREAMING_SNAKE_CASE      :str					,						SCREAMING_SNAKE_CASE      :Union[str, Any]=None					,						SCREAMING_SNAKE_CASE      :Any="uniform_average"     )	-> List[Any]:




             '''simple docstring'''
             _a   :			Tuple					 =mean_absolute_error(SCREAMING_SNAKE_CASE					,						SCREAMING_SNAKE_CASE					,						sample_weight=SCREAMING_SNAKE_CASE					,						multioutput=SCREAMING_SNAKE_CASE     )

             return {"mae": mae_score}


