# LICENSE HEADER MANAGED BY add-license-header
#
# Copyright 2018 Kornia Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from typing import Any, Dict, Optional, Tuple, Union

import torch
from torch import Tensor

from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _PicklableCompileMixin
from kornia.augmentation.utils import _check_filter_min_size
from kornia.constants import BorderType
from kornia.filters import gaussian_blur2d
from kornia.filters.kernels import _check_kernel_size, _unpack_2d_ks


class RandomGaussianBlur(_PicklableCompileMixin, IntensityAugmentationBase2D):
    r"""Blur images with a Gaussian kernel of random sigma, applied per sample with probability ``p`` (default 0.5).

    ``output = RandomGaussianBlur(kernel_size, sigma, ...)(input)`` convolves each selected ``(B, C, H, W)`` image
    with separable Gaussian weights.

    The standard deviation is sampled for each instance.

    .. image:: _static/img/RandomGaussianBlur.png

    .. note::
        Unlike torchvision's ``GaussianBlur``, which blurs every image, this class blurs each sample with probability
        ``p``, 0.5 by default; with ``same_on_batch=True`` one draw decides for the whole batch. Pass ``p=1.0`` to blur
        every sample.

    See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.

    Args:
        kernel_size: the size of the kernel.
        sigma: the range for the standard deviation of the kernel.
        border_type: the padding mode to be applied before convolving.
          The expected modes are: ``constant``, ``reflect``, ``replicate`` or ``circular``.
        separable: run as composition of two 1d-convolutions.
        same_on_batch: apply the same transformation across the batch.
        p: probability of applying the transformation to each sample.
        keepdim: whether to keep the output shape the same as input (True) or broadcast it
                 to the batch form (False).

    Shape:
        - Input: ``(C, H, W)`` or ``(B, C, H, W)``, Optional: ``(B, 3, 3)``
        - Output: ``(B, C, H, W)``

    Convention:
        - this operation is range-independent: it does not clamp the input into ``[0, 1]``.
        - ``kernel_size`` is ``(kH, kW)``: rows, then columns, as in :func:`kornia.filters.gaussian_blur2d`. An
          even entry is not rounded up: the forward pass raises that function's odd-size error.
        - ``sigma`` is drawn once per sample, as a single scalar used for both axes, and a drawn ``0`` raises on
          the forward pass. Both axes get that sigma even when a rectangular ``kernel_size`` gives them different
          supports, and a support short enough to truncate the Gaussian narrows the blur along its axis.
        - the defaults ``separable=True`` and ``border_type="reflect"`` are the function's own defaults.
        - the output is not clamped. At the default ``border_type="reflect"`` every output value is a weighted
          mean of input values and stays between the input's extremes, up to the rounding of the kernel weights;
          ``border_type="constant"`` pads with zeros, which pulls a border pixel toward ``0``.

    .. note::
        The padding sets a minimum image size: at ``border_type="reflect"`` each spatial axis must be longer than
        the kernel's radius along it, and at ``"circular"`` at least that long; a smaller image raises a
        ``ValueError`` naming the class, the kernel and the input shape. ``"constant"`` and ``"replicate"`` run
        down to a single pixel.

    .. note::
        This function internally uses :func:`kornia.filters.gaussian_blur2d`.

    See Also:
        - :class:`RandomBoxBlur`: uses uniform box-filter weights.
        - :class:`RandomMedianBlur`: uses the median rather than a weighted average.
        - :class:`RandomMotionBlur`: uses a directional motion kernel.

    Examples:
        >>> rng = torch.manual_seed(0)
        >>> input = torch.rand(1, 1, 5, 5)
        >>> blur = RandomGaussianBlur((3, 3), (0.1, 2.0), p=1.)
        >>> blur(input)
        tensor([[[[0.5941, 0.5833, 0.5022, 0.4384, 0.3934],
                  [0.5310, 0.4964, 0.4113, 0.3637, 0.3472],
                  [0.4991, 0.4997, 0.4312, 0.3620, 0.3081],
                  [0.6082, 0.5667, 0.4954, 0.3825, 0.3508],
                  [0.7042, 0.6849, 0.6275, 0.4753, 0.4105]]]])

    To apply the exact augmenation again, you may take the advantage of the previous parameter state:
        >>> input = torch.randn(1, 3, 32, 32)
        >>> aug = RandomGaussianBlur((3, 3), (0.1, 2.0), p=1.)
        >>> (aug(input) == aug(input, params=aug._params)).all()
        tensor(True)

    """

    def __init__(
        self,
        kernel_size: Union[Tuple[int, int], int],
        sigma: Union[Tuple[float, float], Tensor],
        border_type: str = "reflect",
        separable: bool = True,
        same_on_batch: bool = False,
        p: float = 0.5,
        keepdim: bool = False,
    ) -> None:
        super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)

        self.flags = {
            "kernel_size": kernel_size,
            "separable": separable,
            "border_type": BorderType.get(border_type),
        }
        self._param_generator = rg.RandomGaussianBlurGenerator(sigma)

        self._gaussian_blur2d_fn = gaussian_blur2d

    def apply_transform(
        self,
        input: Tensor,
        params: Dict[str, Tensor],
        flags: Dict[str, Any],
        transform: Optional[Tensor] = None,
    ) -> Tensor:
        # An even entry is wrong at every image size, so raise gaussian_blur2d's own kernel error
        # before the size guard below can blame the image for it.
        _check_kernel_size(_unpack_2d_ks(self.flags["kernel_size"]), 0)
        _check_filter_min_size(
            "RandomGaussianBlur",
            input,
            self.flags["kernel_size"],
            border_type=self.flags["border_type"].name.lower(),
        )
        sigma = params["sigma"].unsqueeze(-1).expand(-1, 2)
        if self.same_on_batch:
            # Every sample shares one sigma, so pass a single (1, 2) sigma: gaussian_blur2d then
            # builds one kernel and convolves the batch depthwise (groups=C) instead of B distinct
            # kernels (groups=B*C). Same result, far less kernel-construction and conv work.
            sigma = sigma[:1]
        return self._gaussian_blur2d_fn(
            input,
            kernel_size=self.flags["kernel_size"],
            sigma=sigma,
            border_type=self.flags["border_type"].name.lower(),
            separable=self.flags["separable"],
        )

    def compile(
        self,
        *,
        fullgraph: bool = False,
        dynamic: bool = False,
        backend: str = "inductor",
        mode: Optional[str] = None,
        options: Optional[Dict[Any, Any]] = None,
        disable: bool = False,
    ) -> "RandomGaussianBlur":
        self._record_compile(
            ["_gaussian_blur2d_fn"],
            {
                "fullgraph": fullgraph,
                "dynamic": dynamic,
                "backend": backend,
                "mode": mode,
                "options": options,
                "disable": disable,
            },
        )
        self._gaussian_blur2d_fn = torch.compile(
            self._gaussian_blur2d_fn,
            fullgraph=fullgraph,
            dynamic=dynamic,
            backend=backend,
            mode=mode,
            options=options,
            disable=disable,
        )
        return self
