§
    ’©ºj$  ã                   óÆ   — d dl mZ d dlmZmZmZ d dlZd dlmZ d dlm	Z	 d dl
mZ d dl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 esdgZddgiZ G d„ de¦  «        ZdS )é    )ÚSequence)ÚAnyÚOptionalÚUnionN)ÚTensor)ÚModule)ÚNoTrainInceptionV3)ÚMetric)Úrank_zero_warn)Údim_zero_cat)Ú_MATPLOTLIB_AVAILABLEÚ_TORCH_FIDELITY_AVAILABLE)Ú_AX_TYPEÚ_PLOT_OUT_TYPEúInceptionScore.plot)ÚInceptionScorer   Útorch_fidelityc                   ó&  ‡ — 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<   eed	<   eed
<   d
Zeed<   	 	 	 ddeeeef         dedededdf
ˆ fd„Zdeddfd„Zdeeef         fd„Z	 ddeeeee         f                  dee         defd„Zˆ xZS )r   aÜ  Calculate the Inception Score (IS) which is used to access how realistic generated images are.

    .. math::
        IS = exp(\mathbb{E}_x KL(p(y | x ) || p(y)))

    where :math:`KL(p(y | x) || p(y))` is the KL divergence between the conditional distribution :math:`p(y|x)`
    and the marginal distribution :math:`p(y)`. Both the conditional and marginal distribution is calculated
    from features extracted from the images. The score is calculated on random splits of the images such that
    both a mean and standard deviation of the score are returned. The metric was originally proposed in
    `inception ref1`_.

    Using the default feature extraction (Inception v3 using the original weights from `inception ref2`_), the input
    is expected to be mini-batches of 3-channel RGB images of shape ``(3xHxW)``. If argument ``normalize``
    is ``True`` images are expected to be dtype ``float`` and have values in the ``[0,1]`` range, else if
    ``normalize`` is set to ``False`` images are expected to have dtype uint8 and take values in the ``[0, 255]``
    range. All images will be resized to 299 x 299 which is the size of the original training data.

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

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

    - ``imgs`` (:class:`~torch.Tensor`): tensor with images feed to the feature extractor

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

    - ``inception_mean`` (:class:`~torch.Tensor`): float scalar tensor with mean inception score over subsets
    - ``inception_std`` (:class:`~torch.Tensor`): float scalar tensor with standard deviation of inception score
      over subsets

    Args:
        feature:
            Either an str, integer or ``nn.Module``:

            - an str or integer will indicate the inceptionv3 feature layer to choose. Can be one of the following:
              'logits_unbiased', 64, 192, 768, 2048
            - an ``nn.Module`` for using a custom feature extractor. Expects that its forward method returns
              an ``(N,d)`` matrix where ``N`` is the batch size and ``d`` is the feature size.

        splits: integer determining how many splits the inception score calculation should be split among
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Raises:
        ValueError:
            If ``feature`` is set to an ``str`` or ``int`` and ``torch-fidelity`` is not installed
        ValueError:
            If ``feature`` is set to an ``str`` or ``int`` and not one of ``('logits_unbiased', 64, 192, 768, 2048)``
        TypeError:
            If ``feature`` is not an ``str``, ``int`` or ``torch.nn.Module``

    Example:
        >>> from torch import rand
        >>> from torchmetrics.image.inception import InceptionScore
        >>> inception = InceptionScore()
        >>> # generate some images
        >>> imgs = torch.randint(0, 255, (100, 3, 299, 299), dtype=torch.uint8)
        >>> inception.update(imgs)
        >>> inception.compute()
        (tensor(1.0549), tensor(0.0121))

    FÚis_differentiableTÚhigher_is_betterÚfull_state_updateg        Úplot_lower_boundÚfeaturesÚ	inceptionÚfeature_networkÚlogits_unbiasedé
   ÚfeatureÚsplitsÚ	normalizeÚkwargsÚreturnNc                 ó6  •—  t          ¦   «         j        di |¤Ž t          dt          ¦  «         t	          |t
          t          f¦  «        rWt          st          d¦  «        ‚d}||vrt          d|› d|› d�¦  «        ‚t          dt          |¦  «        g¬¦  «        | _        n,t	          |t          ¦  «        r|| _        nt          d	¦  «        ‚t	          |t          ¦  «        st          d
¦  «        ‚|| _        || _        |                      dg d ¬¦  «         d S )NzMetric `InceptionScore` will save all extracted features in buffer. For large datasets this may lead to large memory footprint.z—InceptionScore metric requires that `Torch-fidelity` is installed. Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`.)r   é@   éÀ   i   i   z3Integer input to argument `feature` must be one of z
, but got ú.zinception-v3-compat)ÚnameÚfeatures_listz'Got unknown input to argument `feature`z*Argument `normalize` expected to be a boolr   )Údist_reduce_fx© )ÚsuperÚ__init__r   ÚUserWarningÚ
isinstanceÚstrÚintr   ÚModuleNotFoundErrorÚ
ValueErrorr	   r   r   Ú	TypeErrorÚboolr    r   Ú	add_state)Úselfr   r   r    r!   Úvalid_int_inputÚ	__class__s         €úl/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/torchmetrics/image/inception.pyr,   zInceptionScore.__init__m   sQ  ø€ ð 	�‰ŒÔÐ"Ð"˜6Ð"Ð"Ð"åðKåñ	
ô 	
ð 	
õ �g¥¥S˜zÑ*Ô*ð 	GÝ,ð Ý)ðlñô ð ð FˆOØ˜oÐ-Ð-Ý ØoÈ/ÐoÐoÐelÐoÐoÐoñô ð õ 0Ð5JÕ[^Ð_fÑ[gÔ[gÐZhÐiÑiÔiˆDŒNˆNÝ˜¥Ñ(Ô(ð 	GØ$ˆDŒNˆNåÐEÑFÔFÐFå˜)¥TÑ*Ô*ð 	KÝÐIÑJÔJÐJØ"ˆŒàˆŒØ�Š�z 2°dˆÑ;Ô;Ð;Ð;Ð;ó    Úimgsc                 ó¤   — | j         r|dz                       ¦   «         n|}|                      |¦  «        }| j                             |¦  «         dS )z)Update the state with extracted features.éÿ   N)r    Úbyter   r   Úappend)r6   r;   r   s      r9   ÚupdatezInceptionScore.update•   sP   € à&*¤nÐ>��s‘
× Ò Ñ"Ô"Ð"¸$ˆØ—>’> $Ñ'Ô'ˆØŒ×Ò˜XÑ&Ô&Ð&Ð&Ð&r:   c                 ó  — t          | j        ¦  «        }t          j        |j        d         ¦  «        }||         }|                     d¬¦  «        }|                     d¬¦  «        }|                     | j        d¬¦  «        }|                     | j        d¬¦  «        }d„ |D ¦   «         }d„ t          |||¦  «        D ¦   «         }d„ |D ¦   «         }t          j
        |¦  «        }|                     ¦   «         |                     ¦   «         fS )zCompute metric.r   é   ©Údimc                 ó<   — g | ]}|                      d d¬¦  «        ‘ŒS )r   T)rD   Úkeepdim)Úmean)Ú.0Úps     r9   ú
<listcomp>z*InceptionScore.compute.<locals>.<listcomp>«   s(   € Ð?Ð?Ð?°Q�Q—V’V ¨4�VÑ0Ô0Ð?Ð?Ð?r:   c                 óJ   — g | ] \  }}}|||                      ¦   «         z
  z  ‘Œ!S r*   )Úlog)rH   rI   Úlog_pÚm_ps       r9   rJ   z*InceptionScore.compute.<locals>.<listcomp>¬   s0   € Ð[Ð[Ð[©=¨1¨e°Sˆq�E˜CŸGšG™IœIÑ%Ñ&Ð[Ð[Ð[r:   c                 ó‚   — g | ]<}|                      d ¬¦  «                             ¦   «                              ¦   «         ‘Œ=S )rB   rC   )ÚsumrG   Úexp)rH   Úks     r9   rJ   z*InceptionScore.compute.<locals>.<listcomp>­   s<   € Ð6Ð6Ð6¨Qˆq�uŠu˜ˆu‰|Œ|× Ò Ñ"Ô"×&Ò&Ñ(Ô(Ð6Ð6Ð6r:   )r   r   ÚtorchÚrandpermÚshapeÚsoftmaxÚlog_softmaxÚchunkr   ÚzipÚstackrG   Ústd)r6   r   ÚidxÚprobÚlog_probÚ	mean_probÚkl_Úkls           r9   ÚcomputezInceptionScore.compute›   s  € å ¤Ñ.Ô.ˆåŒn˜Xœ^¨AÔ.Ñ/Ô/ˆØ˜C”=ˆð ×Ò AÐÑ&Ô&ˆØ×'Ò'¨AÐ'Ñ.Ô.ˆð �zŠz˜$œ+¨1ˆzÑ-Ô-ˆØ—>’> $¤+°1�>Ñ5Ô5ˆð @Ð?¸$Ð?Ñ?Ô?ˆ	Ø[Ð[½CÀÀhÐPYÑ<ZÔ<ZÐ[Ñ[Ô[ˆØ6Ð6°#Ð6Ñ6Ô6ˆÝŒ[˜ÑÔˆð �wŠw‰yŒy˜"Ÿ&š&™(œ(Ð"Ð"r:   ÚvalÚaxc                 óf   — |p|                       ¦   «         d         }|                      ||¦  «        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.inception import InceptionScore
            >>> metric = InceptionScore()
            >>> metric.update(torch.randint(0, 255, (50, 3, 299, 299), dtype=torch.uint8))
            >>> fig_, ax_ = metric.plot()  # the returned plot only shows the mean value by default

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> import torch
            >>> from torchmetrics.image.inception import InceptionScore
            >>> metric = InceptionScore()
            >>> values = [ ]
            >>> for _ in range(3):
            ...     # we index by 0 such that only the mean value is plotted
            ...     values.append(metric(torch.randint(0, 255, (50, 3, 299, 299), dtype=torch.uint8))[0])
            >>> fig_, ax_ = metric.plot(values)

        r   )rb   Ú_plot)r6   rc   rd   s      r9   ÚplotzInceptionScore.plot³   s0   € ðR Ð&�T—\’\‘^”^ AÔ&ˆØ�zŠz˜#˜rÑ"Ô"Ð"r:   )r   r   F)NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r4   Ú__annotations__r   r   r   ÚfloatÚlistr   r   r/   r   r0   r   r,   r   r@   Útuplerb   r   r   r   r   rg   Ú__classcell__)r8   s   @r9   r   r   #   sš  ø€ € € € € € ð>ð >ð@ $Ð�tÐ#Ð#Ñ#Ø!Ð�dÐ!Ð!Ñ!Ø#Ð�tÐ#Ð#Ñ#Ø!Ð�eÐ!Ð!Ñ!à€N€N�NØÐÐÑØ&€O�SÐ&Ð&Ñ&ð ,=ØØð	&<ð &<à�s˜C Ð'Ô(ð&<ð ð&<ð ð	&<ð
 ð&<ð 
ð&<ð &<ð &<ð &<ð &<ð &<ðP'˜6ð ' dð 'ð 'ð 'ð 'ð#˜˜v v˜~Ô.ð #ð #ð #ð #ð2 _cð*#ð *#Ø˜E &¨(°6Ô*:Ð":Ô;Ô<ð*#ØIQÐRZÔI[ð*#à	ð*#ð *#ð *#ð *#ð *#ð *#ð *#ð *#r:   r   )Úcollections.abcr   Útypingr   r   r   rS   r   Útorch.nnr   Útorchmetrics.image.fidr	   Útorchmetrics.metricr
   Útorchmetrics.utilitiesr   Útorchmetrics.utilities.datar   Útorchmetrics.utilities.importsr   r   Útorchmetrics.utilities.plotr   r   Ú__doctest_skip__Ú__doctest_requires__r   r*   r:   r9   ú<module>r|      s=  ðð %Ð $Ð $Ð $Ð $Ð $Ø 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'à €€€Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð à 5Ð 5Ð 5Ð 5Ð 5Ð 5Ø &Ð &Ð &Ð &Ð &Ð &Ø 1Ð 1Ð 1Ð 1Ð 1Ð 1Ø 4Ð 4Ð 4Ð 4Ð 4Ð 4Ø [Ð [Ð [Ð [Ð [Ð [Ð [Ð [Ø @Ð @Ð @Ð @Ð @Ð @Ð @Ð @àð /Ø-Ð.Ðð BÐDTÐCUÐVÐ ðz#ð z#ð z#ð z#ð z#�Vñ z#ô z#ð z#ð z#ð z#r:   