o
    ôj�.  ã                   @   sº  d dl mZmZmZmZmZ d dlZd dlZd dlZd dlm	Z	m
Z
 d dlmZ ddlmZ ddlmZ ejjd	e
d
ee
 de
fdd„ƒZ			d2dededededef
dd„ZG dd„ dƒZdee
 de
fdd„Zde
dee defdd „Zejjd!ee
 d"eeeef  dededeee ef f
d#d$„ƒZejjd%eee
f d&ee dee
 fd'd(„ƒZejjd)ee
 dee
 d*ee d+ed,eee  d-ee de
fd.d/„ƒZG d0d1„ d1e	jƒZ dS )3é    )ÚDictÚListÚOptionalÚTupleÚUnionN)ÚnnÚTensor©Úbox_areaé   )Ú_log_api_usage_onceé   )Ú	roi_alignÚlevelsÚunmerged_resultsÚreturnc              	   C   sÀ   |d }|j |j}}tj|  d¡| d¡| d¡| d¡f||d�}tt|ƒƒD ]4}t | |k¡d  dddd¡}| 	| d¡||  d¡||  d¡||  d¡¡}| 
d||| ¡}q)|S )Nr   r   r   é   ©ÚdtypeÚdeviceéÿÿÿÿ)r   r   ÚtorchÚzerosÚsizeÚrangeÚlenÚwhereÚviewÚexpandÚscatter)r   r   Zfirst_resultr   r   ÚresÚlevelÚindex© r#   úh/var/www/html/academy/tools/voices/clone/sv-venv/lib/python3.10/site-packages/torchvision/ops/poolers.pyÚ_onnx_merge_levels   s   &ÿür%   éà   é   ç�íµ ÷Æ°>Úk_minÚk_maxÚcanonical_scaleÚcanonical_levelÚepsc                 C   s   t | ||||ƒS ©N)ÚLevelMapper)r)   r*   r+   r,   r-   r#   r#   r$   ÚinitLevelMapper%   s   r0   c                   @   sL   e Zd ZdZ			ddedededed	ef
d
d„Zdee defdd„Z	dS )r/   zöDetermine which FPN level each RoI in a set of RoIs should map to based
    on the heuristic in the FPN paper.

    Args:
        k_min (int)
        k_max (int)
        canonical_scale (int)
        canonical_level (int)
        eps (float)
    r&   r'   r(   r)   r*   r+   r,   r-   c                 C   s"   || _ || _|| _|| _|| _d S r.   )r)   r*   Ús0Úlvl0r-   )Úselfr)   r*   r+   r,   r-   r#   r#   r$   Ú__init__;   s
   
zLevelMapper.__init__Úboxlistsr   c                 C   sv   t  t  dd„ |D ƒ¡¡}t  | jt  || j ¡ t j| j|j	d� ¡}t j
|| j| jd�}| t j¡| j  t j¡S )z<
        Args:
            boxlists (list[BoxList])
        c                 S   s   g | ]}t |ƒ‘qS r#   r	   )Ú.0Zboxlistr#   r#   r$   Ú
<listcomp>O   s    z(LevelMapper.__call__.<locals>.<listcomp>©r   )ÚminÚmax)r   ÚsqrtÚcatÚfloorr2   Úlog2r1   Útensorr-   r   Úclampr)   r*   ÚtoÚint64)r3   r5   ÚsZtarget_lvlsr#   r#   r$   Ú__call__I   s   .zLevelMapper.__call__N©r&   r'   r(   )
Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚintÚfloatr4   r   r   rD   r#   r#   r#   r$   r/   /   s"    úþýüû
úr/   Úboxesc                    sT   t j| dd�}|j|j‰ ‰t j‡ ‡fdd„t| ƒD ƒdd�}t j||gdd�}|S )Nr   )Údimc              	      s6   g | ]\}}t j|d d …d d…f |ˆt jˆ d�‘qS )Nr   )r   Úlayoutr   )r   Ú	full_likeÚstrided)r6   ÚiÚb©r   r   r#   r$   r7   [   s   6 z*_convert_to_roi_format.<locals>.<listcomp>r   )r   r<   r   r   Ú	enumerate)rL   Úconcat_boxesÚidsÚroisr#   rS   r$   Ú_convert_to_roi_formatW   s   þrX   ÚfeatureÚoriginal_sizec                 C   sb   | j dd … }g }t||ƒD ]\}}t|ƒt|ƒ }dtt |¡ ¡  ¡ ƒ }| |¡ q|d S )Néþÿÿÿr   r   )ÚshapeÚziprK   r   r?   r>   ÚroundÚappend)rY   rZ   r   Zpossible_scalesÚs1Ús2Zapprox_scaleÚscaler#   r#   r$   Ú_infer_scaleb   s   rc   ÚfeaturesÚimage_shapesc                    s´   |st dƒ‚d}d}|D ]}t|d |ƒ}t|d |ƒ}q||f‰ ‡ fdd„| D ƒ}t tj|d tjd�¡ ¡  }t tj|d tjd�¡ ¡  }	tt|ƒt|	ƒ||d�}
||
fS )	Nzimages list should not be emptyr   r   c                    s   g | ]}t |ˆ ƒ‘qS r#   )rc   )r6   Úfeat©Zoriginal_input_shaper#   r$   r7   z   s    z!_setup_scales.<locals>.<listcomp>r8   r   ©r+   r,   )	Ú
ValueErrorr:   r   r>   r?   Úfloat32Úitemr0   rJ   )rd   re   r+   r,   Zmax_xZmax_yr\   ÚscalesZlvl_minZlvl_maxÚ
map_levelsr#   rg   r$   Ú_setup_scalesm   s$     ürn   ÚxÚfeatmap_namesc                 C   s,   g }|   ¡ D ]\}}||v r| |¡ q|S r.   )Úitemsr_   )ro   rp   Ú
x_filteredÚkÚvr#   r#   r$   Ú_filter_input‰   s   
€ru   rr   Úoutput_sizeÚsampling_ratiorl   Úmapperc                 C   s"  |du s|du rt dƒ‚t| ƒ}t|ƒ}|dkr%t| d |||d |d�S ||ƒ}t|ƒ}	| d jd }
| d j| d j}}tj|	|
f| ||d�}g }t	t
| |ƒƒD ]1\}\}}t ||k¡d }|| }t|||||d�}t ¡ r}| | |¡¡ qT| |j¡||< qTt ¡ r�t||ƒ}|S )aå  
    Args:
        x_filtered (List[Tensor]): List of input tensors.
        boxes (List[Tensor[N, 4]]): boxes to be used to perform the pooling operation, in
            (x1, y1, x2, y2) format and in the image reference size, not the feature map
            reference. The coordinate must satisfy ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
        output_size (Union[List[Tuple[int, int]], List[int]]): size of the output
        sampling_ratio (int): sampling ratio for ROIAlign
        scales (Optional[List[float]]): If None, scales will be automatically inferred. Default value is None.
        mapper (Optional[LevelMapper]): If none, mapper will be automatically inferred. Default value is None.
    Returns:
        result (Tensor)
    Nz$scales and mapper should not be Noner   r   )rv   Úspatial_scalerw   r   )ri   r   rX   r   r\   r   r   r   r   rT   r]   r   ÚtorchvisionÚ_is_tracingr_   rA   r%   )rr   rL   rv   rw   rl   rx   Ú
num_levelsrW   r   Únum_roisÚnum_channelsr   r   ÚresultZtracing_resultsr!   Zper_level_featurerb   Zidx_in_levelZrois_per_levelZresult_idx_in_levelr#   r#   r$   Ú_multiscale_roi_align’   sT   ûþüù
û	
r€   c                       sª   e Zd ZdZeee  ee dœZdddœdee	 de
eee ee f ded	ed
ef
‡ fdd„Zdee	ef dee deeeef  defdd„Zde	fdd„Z‡  ZS )ÚMultiScaleRoIAligna{  
    Multi-scale RoIAlign pooling, which is useful for detection with or without FPN.

    It infers the scale of the pooling via the heuristics specified in eq. 1
    of the `Feature Pyramid Network paper <https://arxiv.org/abs/1612.03144>`_.
    They keyword-only parameters ``canonical_scale`` and ``canonical_level``
    correspond respectively to ``224`` and ``k0=4`` in eq. 1, and
    have the following meaning: ``canonical_level`` is the target level of the pyramid from
    which to pool a region of interest with ``w x h = canonical_scale x canonical_scale``.

    Args:
        featmap_names (List[str]): the names of the feature maps that will be used
            for the pooling.
        output_size (List[Tuple[int, int]] or List[int]): output size for the pooled region
        sampling_ratio (int): sampling ratio for ROIAlign
        canonical_scale (int, optional): canonical_scale for LevelMapper
        canonical_level (int, optional): canonical_level for LevelMapper

    Examples::

        >>> m = torchvision.ops.MultiScaleRoIAlign(['feat1', 'feat3'], 3, 2)
        >>> i = OrderedDict()
        >>> i['feat1'] = torch.rand(1, 5, 64, 64)
        >>> i['feat2'] = torch.rand(1, 5, 32, 32)  # this feature won't be used in the pooling
        >>> i['feat3'] = torch.rand(1, 5, 16, 16)
        >>> # create some random bounding boxes
        >>> boxes = torch.rand(6, 4) * 256; boxes[:, 2:] += boxes[:, :2]
        >>> # original image size, before computing the feature maps
        >>> image_sizes = [(512, 512)]
        >>> output = m(i, [boxes], image_sizes)
        >>> print(output.shape)
        >>> torch.Size([6, 5, 3, 3])

    )rl   rm   r&   r'   rh   rp   rv   rw   r+   r,   c                   sV   t ƒ  ¡  t| ƒ t|tƒr||f}|| _|| _t|ƒ| _d | _	d | _
|| _|| _d S r.   )Úsuperr4   r   Ú
isinstancerJ   rp   rw   Útuplerv   rl   rm   r+   r,   )r3   rp   rv   rw   r+   r,   ©Ú	__class__r#   r$   r4     s   
	


zMultiScaleRoIAlign.__init__ro   rL   re   r   c                 C   sT   t || jƒ}| jdu s| jdu rt||| j| jƒ\| _| _t||| j| j	| j| jƒS )a  
        Args:
            x (OrderedDict[Tensor]): feature maps for each level. They are assumed to have
                all the same number of channels, but they can have different sizes.
            boxes (List[Tensor[N, 4]]): boxes to be used to perform the pooling operation, in
                (x1, y1, x2, y2) format and in the image reference size, not the feature map
                reference. The coordinate must satisfy ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
            image_shapes (List[Tuple[height, width]]): the sizes of each image before they
                have been fed to a CNN to obtain feature maps. This allows us to infer the
                scale factor for each one of the levels to be pooled.
        Returns:
            result (Tensor)
        N)
ru   rp   rl   rm   rn   r+   r,   r€   rv   rw   )r3   ro   rL   re   rr   r#   r#   r$   Úforward!  s   ÿúzMultiScaleRoIAlign.forwardc                 C   s&   | j j› d| j› d| j› d| j› d�S )Nz(featmap_names=z, output_size=z, sampling_ratio=ú))r†   rF   rp   rv   rw   )r3   r#   r#   r$   Ú__repr__C  s   ÿÿÿzMultiScaleRoIAlign.__repr__)rF   rG   rH   rI   r   r   rK   r/   Ú__annotations__Ústrr   rJ   r   r4   r   r   r‡   r‰   Ú__classcell__r#   r#   r…   r$   r�   æ   s4    #ùþýüúù
þýü
û"r�   rE   )!Útypingr   r   r   r   r   r   Útorch.fxrz   r   r   Ztorchvision.ops.boxesr
   Úutilsr   r   ÚjitÚunusedr%   rJ   rK   r0   r/   rX   rc   ÚfxÚwraprn   r‹   ru   r€   ÚModuler�   r#   r#   r#   r$   Ú<module>   st    ûÿþýü
û
(ÿÿÿÿþ(ÿþýü
ûúùS