§
    ’©ºj!  ã                   ó   — d dl mZ d dlmZmZmZmZ d dlmZ d dl	m
Z
 d dlmZmZmZmZ d dlmZ d dlmZ d dlmZmZ d d	lmZmZ d d
lmZmZ esdgZerdd„Zer ee¦  «        sddgZnddgZ G d„ de¦  «        ZdS )é    )ÚSequence)ÚAnyÚClassVarÚOptionalÚUnion)ÚTensor)ÚLiteral)Ú_LPIPSÚ_lpips_computeÚ_lpips_updateÚ_NoTrainLpips)ÚMetric)Údim_zero_cat)Ú_SKIP_SLOW_DOCTESTÚ_try_proceed_with_timeout)Ú_MATPLOTLIB_AVAILABLEÚ_TORCHVISION_AVAILABLE)Ú_AX_TYPEÚ_PLOT_OUT_TYPEz*LearnedPerceptualImagePatchSimilarity.plotÚreturnNc                  ó(   — t          dd¬¦  «         d S )NTÚvgg)Ú
pretrainedÚnet)r
   © ó    úg/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/torchmetrics/image/lpip.pyÚ_download_lpipsr       s   € Ý˜$ EÐ*Ñ*Ô*Ð*Ð*Ð*r   Ú%LearnedPerceptualImagePatchSimilarityc                   ód  ‡ — e Zd ZU dZdZeed<   dZeed<   dZeed<   dZ	e
ed<   d	Ze
ed
<   ee         ed<   dZeed<   dgZeee                  ed<   	 	 	 d!ded         deed                  dededdf
ˆ fd„Zdededdfd„Zdefd„Z	 d"deeeee         f                  dee         defd „Zˆ xZS )#r   a–  The Learned Perceptual Image Patch Similarity (`LPIPS_`) calculates perceptual similarity between two images.

    LPIPS essentially computes the similarity between the activations of two image patches for some pre-defined network.
    This measure has been shown to match human perception well. A low LPIPS score means that image patches are
    perceptual similar.

    Both input image patches are expected to have shape ``(N, 3, H, W)``. The minimum size of `H, W` depends on the
    chosen backbone (see `net_type` arg).

    .. hint::
        Using this metrics requires you to have ``torchvision`` package installed. Either install as
        ``pip install torchmetrics[image]`` or ``pip install torchvision``.

    As input to ``forward`` and ``update`` the metric accepts the following input

    - ``img1`` (:class:`~torch.Tensor`): tensor with images of shape ``(N, 3, H, W)``
    - ``img2`` (:class:`~torch.Tensor`): tensor with images of shape ``(N, 3, H, W)``

    As output of `forward` and `compute` the metric returns the following output

    - ``lpips`` (:class:`~torch.Tensor`): returns float scalar tensor with average LPIPS value over samples

    Args:
        net_type: str indicating backbone network type to use. Choose between `'alex'`, `'vgg'` or `'squeeze'`
        reduction: str indicating how to reduce over the batch dimension. Choose between `'sum'`, `'mean'`,`'none'`
            or `None`.
        normalize: by default this is ``False`` meaning that the input is expected to be in the [-1,1] range. If set
            to ``True`` will instead expect input to be in the ``[0,1]`` range.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Raises:
        ModuleNotFoundError:
            If ``torchvision`` package is not installed
        ValueError:
            If ``net_type`` is not one of ``"vgg"``, ``"alex"`` or ``"squeeze"``
        ValueError:
            If ``reduction`` is not one of ``"mean"`` or ``"sum"``

    Example:
        >>> from torch import rand
        >>> from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
        >>> lpips = LearnedPerceptualImagePatchSimilarity(net_type='squeeze')
        >>> # LPIPS needs the images to be in the [-1, 1] range.
        >>> img1 = (rand(10, 3, 100, 100) * 2) - 1
        >>> img2 = (rand(10, 3, 100, 100) * 2) - 1
        >>> lpips(img1, img2)
        tensor(0.1024)

        >>> from torch import rand, Generator
        >>> from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
        >>> gen = Generator().manual_seed(42)
        >>> lpips = LearnedPerceptualImagePatchSimilarity(net_type='squeeze', reduction='none')
        >>> # LPIPS needs the images to be in the [-1, 1] range.
        >>> img1 = (rand(2, 3, 100, 100, generator=gen) * 2) - 1
        >>> img2 = (rand(2, 3, 100, 100, generator=gen) * 2) - 1
        >>> lpips(img1, img2)
        tensor([0.1024, 0.0938])

    TÚis_differentiableFÚhigher_is_betterÚfull_state_updateg        Úplot_lower_boundg      ð?Úplot_upper_boundÚ
all_scoresr   Úfeature_networkÚ__jit_ignored_attributes__ÚalexÚmeanÚnet_type©r   r)   ÚsqueezeÚ	reduction)Úsumr*   ÚnoneÚ	normalizeÚkwargsr   Nc                 ó˜  •—  t          ¦   «         j        di |¤Ž t          st          d¦  «        ‚d}||vrt	          d|› d|› d�¦  «        ‚t          |¬¦  «        | _        d}||vrt	          d|› d|› �¦  «        ‚|| _        t          |t          ¦  «        st	          d	|› �¦  «        ‚|| _
        |                      d
g d ¬¦  «         d S )Nz†LPIPS metric requires that torchvision is installed. Either install as `pip install torchmetrics[image]` or `pip install torchvision`.r,   z#Argument `net_type` must be one of z
, but got ú.)r   )r*   r/   r0   Nz$Argument `reduction` must be one of z/Argument `normalize` should be an bool but got r&   )ÚdefaultÚdist_reduce_fxr   )ÚsuperÚ__init__r   ÚModuleNotFoundErrorÚ
ValueErrorr   r   r.   Ú
isinstanceÚboolr1   Ú	add_state)Úselfr+   r.   r1   r2   Úvalid_net_typeÚvalid_reductionÚ	__class__s          €r   r8   z.LearnedPerceptualImagePatchSimilarity.__init__r   s  ø€ ð 	�‰ŒÔÐ"Ð"˜6Ð"Ð"Ð"å%ð 	Ý%ðeñô ð ð
 4ˆØ˜>Ð)Ð)ÝÐhÀ>ÐhÐhÐ]eÐhÐhÐhÑiÔiÐiÝ  XÐ.Ñ.Ô.ˆŒà7ˆØ˜OÐ+Ð+ÝÐjÀOÐjÐjÐ_hÐjÐjÑkÔkÐkØ"ˆŒå˜)¥TÑ*Ô*ð 	\ÝÐZÈyÐZÐZÑ[Ô[Ð[Ø"ˆŒà�Š�|¨RÀˆÑEÔEÐEÐEÐEr   Úimg1Úimg2c                 ót   — t          ||| j        | j        ¬¦  «        }| j                             |¦  «         dS )z(Update internal states with lpips score.)r   r1   N)r   r   r1   r&   Úappend)r>   rB   rC   Úlosss       r   Úupdatez,LearnedPerceptualImagePatchSimilarity.update‘   s8   € å˜T 4¨T¬XÀÄÐPÑPÔPˆØŒ×Ò˜tÑ$Ô$Ð$Ð$Ð$r   c                 óV   — t          | j        ¦  «        }t          || j        ¬¦  «        S )z+Compute final perceptual similarity metric.)r.   )r   r&   r   r.   )r>   Úscoress     r   Úcomputez-LearnedPerceptualImagePatchSimilarity.compute–   s&   € å˜dœoÑ.Ô.ˆÝ˜f°´Ð?Ñ?Ô?Ð?r   ÚvalÚaxc                 ó.   — |                       ||¦  «        S )a·  Plot a single or multiple values from the metric.

        Args:
            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
                If no value is provided, will automatically call `metric.compute` and plot that result.
            ax: An matplotlib axis object. If provided will add plot to that axis

        Returns:
            Figure and Axes object

        Raises:
            ModuleNotFoundError:
                If `matplotlib` is not installed

        .. plot::
            :scale: 75

            >>> # Example plotting a single value
            >>> import torch
            >>> from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
            >>> metric = LearnedPerceptualImagePatchSimilarity(net_type='squeeze')
            >>> metric.update(torch.rand(10, 3, 100, 100), torch.rand(10, 3, 100, 100))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> import torch
            >>> from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
            >>> metric = LearnedPerceptualImagePatchSimilarity(net_type='squeeze')
            >>> values = [ ]
            >>> for _ in range(3):
            ...     values.append(metric(torch.rand(10, 3, 100, 100), torch.rand(10, 3, 100, 100)))
            >>> fig_, ax_ = metric.plot(values)

        )Ú_plot)r>   rK   rL   s      r   Úplotz*LearnedPerceptualImagePatchSimilarity.plot›   s   € ðP �zŠz˜#˜rÑ"Ô"Ð"r   )r)   r*   F)NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r!   r<   Ú__annotations__r"   r#   r$   Úfloatr%   Úlistr   r'   Ústrr(   r   r	   r   r   r8   rG   rJ   r   r   r   r   rO   Ú__classcell__)rA   s   @r   r   r   )   s×  ø€ € € € € € ð:ð :ðx #Ð�tÐ"Ð"Ñ"Ø"Ð�dÐ"Ð"Ñ"Ø#Ð�tÐ#Ð#Ñ#Ø!Ð�eÐ!Ð!Ñ!Ø!Ð�eÐ!Ð!Ñ!à�V”ÐÐÑØ €O�SÐ Ð Ñ ð 8=°gÐ ¨¨c¬Ô 3Ð=Ð=Ñ=ð 7=Ø>DØð	Fð FàÐ2Ô3ðFð ˜GÐ$9Ô:Ô;ðFð ð	Fð
 ðFð 
ðFð Fð Fð Fð Fð Fð>%˜6ð %¨ð %°Dð %ð %ð %ð %ð
@˜ð @ð @ð @ð @ð _cð(#ð (#Ø˜E &¨(°6Ô*:Ð":Ô;Ô<ð(#ØIQÐRZÔI[ð(#à	ð(#ð (#ð (#ð (#ð (#ð (#ð (#ð (#r   )r   N) Úcollections.abcr   Útypingr   r   r   r   Útorchr   Útyping_extensionsr	   Ú#torchmetrics.functional.image.lpipsr
   r   r   r   Útorchmetrics.metricr   Útorchmetrics.utilitiesr   Útorchmetrics.utilities.checksr   r   Útorchmetrics.utilities.importsr   r   Útorchmetrics.utilities.plotr   r   Ú__doctest_skip__r   r   r   r   r   ú<module>rd      s–  ðð %Ð $Ð $Ð $Ð $Ð $Ø 1Ð 1Ð 1Ð 1Ð 1Ð 1Ð 1Ð 1Ð 1Ð 1Ð 1Ð 1à Ð Ð Ð Ð Ð Ø %Ð %Ð %Ð %Ð %Ð %à dÐ dÐ dÐ dÐ dÐ dÐ dÐ dÐ dÐ dÐ dÐ dØ &Ð &Ð &Ð &Ð &Ð &Ø /Ð /Ð /Ð /Ð /Ð /Ø WÐ WÐ WÐ WÐ WÐ WÐ WÐ WØ XÐ XÐ XÐ XÐ XÐ XÐ XÐ XØ @Ð @Ð @Ð @Ð @Ð @Ð @Ð @àð FØDÐEÐàð oð+ð +ð +ð +ð ð sÐ";Ð";¸OÑ"LÔ"Lð sØCÐEqÐrÐøà?ÐAmÐnÐðZ#ð Z#ð Z#ð Z#ð Z#¨Fñ Z#ô Z#ð Z#ð Z#ð Z#r   