§
    ’©ºjK!  ã                   ó�   — d dl mZmZmZmZ d dlmZ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 esdgZ G d„ de¦  «        Zd	S )
é    )ÚAnyÚLiteralÚOptionalÚUnion)ÚTensorÚnn)Ú_LPIPS)ÚGeneratorTypeÚ*_perceptual_path_length_validate_argumentsÚ_validate_generator_modelÚperceptual_path_length)ÚMetric)Ú_TORCHVISION_AVAILABLEÚPerceptualPathLengthc                   óB  ‡ — e Zd ZU dZdZeed<   dZee         ed<   dZ	eed<   e
j        ed<   dZeed<   	 	 	 	 	 	 	 	 	 d#dedededed         dedee         dee         dee         dee
j        ed         f         deddfˆ fd„Zd eddfd!„Zdeeeef         fd"„Zˆ xZS )$r   a×  Computes the perceptual path length (`PPL`_) of a generator model.

    The perceptual path length can be used to measure the consistency of interpolation in latent-space models. It is
    defined as

    .. math::
        PPL = \mathbb{E}\left[\frac{1}{\epsilon^2} D(G(I(z_1, z_2, t)), G(I(z_1, z_2, t+\epsilon)))\right]

    where :math:`G` is the generator, :math:`I` is the interpolation function, :math:`D` is a similarity metric,
    :math:`z_1` and :math:`z_2` are two sets of latent points, and :math:`t` is a parameter between 0 and 1. The metric
    thus works by interpolating between two sets of latent points, and measuring the similarity between the generated
    images. The expectation is approximated by sampling :math:`z_1` and :math:`z_2` from the generator, and averaging
    the calculated distanced. The similarity metric :math:`D` is by default the `LPIPS`_ metric, but can be changed by
    setting the `sim_net` argument.

    The provided generator model must have a `sample` method with signature `sample(num_samples: int) -> Tensor` where
    the returned tensor has shape `(num_samples, z_size)`. If the generator is conditional, it must also have a
    `num_classes` attribute. The `forward` method of the generator must have signature `forward(z: Tensor) -> Tensor`
    if `conditional=False`, and `forward(z: Tensor, labels: Tensor) -> Tensor` if `conditional=True`. The returned
    tensor should have shape `(num_samples, C, H, W)` and be scaled to the range [0, 255].

    .. hint::
        Using this metric with the default feature extractor requires that ``torchvision`` is installed.
        Either install as ``pip install torchmetrics[image]`` or ``pip install torchvision``

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

    - ``generator`` (:class:`~torch.nn.Module`):  Generator model, with specific requirements. See above.

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

    - ``ppl_mean`` (:class:`~torch.Tensor`): float scalar tensor with mean PPL value over distances
    - ``ppl_std`` (:class:`~torch.Tensor`): float scalar tensor with std PPL value over distances
    - ``ppl_raw`` (:class:`~torch.Tensor`): float scalar tensor with raw PPL distances

    Args:
        num_samples: Number of samples to use for the PPL computation.
        conditional: Whether the generator is conditional or not (i.e. whether it takes labels as input).
        batch_size: Batch size to use for the PPL computation.
        interpolation_method: Interpolation method to use. Choose from 'lerp', 'slerp_any', 'slerp_unit'.
        epsilon: Spacing between the points on the path between latent points.
        resize: Resize images to this size before computing the similarity between generated images.
        lower_discard: Lower quantile to discard from the distances, before computing the mean and standard deviation.
        upper_discard: Upper quantile to discard from the distances, before computing the mean and standard deviation.
        sim_net: Similarity network to use. Can be a `nn.Module` or one of 'alex', 'vgg', 'squeeze', where the three
            latter options correspond to the pretrained networks from the `LPIPS`_ paper.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Raises:
        ModuleNotFoundError:
            If ``torch-fidelity`` is not installed.
        ValueError:
            If ``num_samples`` is not a positive integer.
        ValueError:
            If `conditional` is not a boolean.
        ValueError:
            If ``batch_size`` is not a positive integer.
        ValueError:
            If ``interpolation_method`` is not one of 'lerp', 'slerp_any', 'slerp_unit'.
        ValueError:
            If ``epsilon`` is not a positive float.
        ValueError:
            If ``resize`` is not a positive integer.
        ValueError:
            If ``lower_discard`` is not a float between 0 and 1 or None.
        ValueError:
            If ``upper_discard`` is not a float between 0 and 1 or None.

    Example::
        >>> import torch
        >>> class DummyGenerator(torch.nn.Module):
        ...    def __init__(self, z_size) -> None:
        ...       super().__init__()
        ...       self.z_size = z_size
        ...       self.model = torch.nn.Sequential(torch.nn.Linear(z_size, 3*128*128), torch.nn.Sigmoid())
        ...    def forward(self, z):
        ...       return 255 * (self.model(z).reshape(-1, 3, 128, 128) + 1)
        ...    def sample(self, num_samples):
        ...      return torch.randn(num_samples, self.z_size)
        >>> generator = DummyGenerator(2)
        >>> ppl = PerceptualPathLength(num_samples=10)
        >>> ppl(generator)
        (tensor(...), tensor(...), tensor([...]))

    FÚis_differentiableTÚhigher_is_betterÚfull_state_updateÚnetÚfeature_networké'  é€   Úlerpç-Cëâ6?é@   ç{®Gáz„?ç®Gáz®ï?ÚvggÚnum_samplesÚconditionalÚ
batch_sizeÚinterpolation_method)r   Ú	slerp_anyÚ
slerp_unitÚepsilonÚresizeÚlower_discardÚupper_discardÚsim_net©Úalexr   ÚsqueezeÚkwargsÚreturnNc
           
      ó¢  •—  t          ¦   «         j        di |
¤Ž t          st          d¦  «        ‚t	          ||||||||¦  «         || _        || _        || _        || _        || _	        || _
        || _        || _        t          |	t          j        ¦  «        r	|	| _        d S |	dv rt#          d|	|¬¦  «        | _        d S t%          d|	› �¦  «        ‚)Nz•Metric `PerceptualPathLength` requires torchvision which is not installed.Install with `pip install torchvision` or `pip install torchmetrics[image]`r*   T)Ú
pretrainedr   r&   zDsim_net must be a nn.Module or one of 'alex', 'vgg', 'squeeze', got © )ÚsuperÚ__init__r   ÚModuleNotFoundErrorr   r   r    r!   r"   r%   r&   r'   r(   Ú
isinstancer   ÚModuler   r	   Ú
ValueError)Úselfr   r    r!   r"   r%   r&   r'   r(   r)   r-   Ú	__class__s              €úy/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/torchmetrics/image/perceptual_path_length.pyr3   zPerceptualPathLength.__init__~   s  ø€ ð 	�‰ŒÔÐ"Ð"˜6Ð"Ð"Ð"Ý%ð 	Ý%ð^ñô ð õ 	3Ø˜ jÐ2FÈÐQWÐYfÐhuñ	
ô 	
ð 	
ð 'ˆÔØ&ˆÔØ$ˆŒØ$8ˆÔ!ØˆŒØˆŒØ*ˆÔØ*ˆÔå�g�rœyÑ)Ô)ð 	oØˆDŒHˆHˆHØÐ2Ð2Ð2Ý¨°7À6ÐJÑJÔJˆDŒHˆHˆHåÐmÐdkÐmÐmÑnÔnÐnó    Ú	generatorc                 ó>   — t          || j        ¦  «         || _        dS )zUpdate the generator model.N)r   r    r<   )r8   r<   s     r:   ÚupdatezPerceptualPathLength.update¤   s    € å! )¨TÔ-=Ñ>Ô>Ð>Ø"ˆŒˆˆr;   c                 ó˜   — t          | j        | j        | j        | j        | j        | j        | j        | j        | j	        | j
        ¬¦
  «
        S )z#Compute the perceptual path length.)
r<   r   r    r"   r%   r&   r'   r(   r)   Údevice)r   r<   r   r    r"   r%   r&   r'   r(   r   r@   )r8   s    r:   ÚcomputezPerceptualPathLength.compute©   sP   € å%Ø”nØÔ(ØÔ(Ø!%Ô!:Ø”LØ”;ØÔ,ØÔ,Ø”HØ”;ð
ñ 
ô 
ð 	
r;   )	r   Fr   r   r   r   r   r   r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚboolÚ__annotations__r   r   r   r   r6   r   ÚstrÚintr   Úfloatr   r   r3   r
   r>   Útupler   rA   Ú__classcell__)r9   s   @r:   r   r       s®  ø€ € € € € € ðTð Tðl $Ð�tÐ#Ð#Ñ#Ø'+Ð�h˜t”nÐ+Ð+Ñ+Ø"Ð�tÐ"Ð"Ñ"à	Œ€N€N�NØ €O�SÐ Ð Ñ ð "Ø!ØØKQØØ "Ø)-Ø)-ØGLð$oð $oàð$oð ð$oð ð	$oð
 &Ð&GÔHð$oð ð$oð ˜”ð$oð   ”ð$oð   ”ð$oð �r”y 'Ð*BÔ"CÐCÔDð$oð ð$oð 
ð$oð $oð $oð $oð $oð $oðL# ð #°$ð #ð #ð #ð #ð

˜˜v v¨vÐ5Ô6ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
r;   N)Útypingr   r   r   r   Útorchr   r   Ú#torchmetrics.functional.image.lpipsr	   Ú4torchmetrics.functional.image.perceptual_path_lengthr
   r   r   r   Útorchmetrics.metricr   Útorchmetrics.utilities.importsr   Ú__doctest_skip__r   r1   r;   r:   ú<module>rT      s  ðð 1Ð 0Ð 0Ð 0Ð 0Ð 0Ð 0Ð 0Ð 0Ð 0Ð 0Ð 0à Ð Ð Ð Ð Ð Ð Ð à 6Ð 6Ð 6Ð 6Ð 6Ð 6ðð ð ð ð ð ð ð ð ð ð ð ð 'Ð &Ð &Ð &Ð &Ð &Ø AÐ AÐ AÐ AÐ AÐ Aàð 0Ø.Ð/ÐðV
ð V
ð V
ð V
ð V
˜6ñ V
ô V
ð V
ð V
ð V
r;   