
    khS.                         d dl Z d dlmZmZ d dlZd dlmZmZ ddlmZ  G d dej                        Z
 G d d	ej                        Zy)
    N)ListOptional)nnTensor   )	ImageListc                   p    e Zd ZdZdeej                     iZ	 	 d fd	Zej                   ej                  d      fdee   dee   dej                  dej                  d	ef
d
Zdej                  dej                  fdZd	ee   fdZdeee      deee      d	ee   fdZdedee   d	ee   fdZ xZS )AnchorGeneratora  
    Module that generates anchors for a set of feature maps and
    image sizes.

    The module support computing anchors at multiple sizes and aspect ratios
    per feature map. This module assumes aspect ratio = height / width for
    each anchor.

    sizes and aspect_ratios should have the same number of elements, and it should
    correspond to the number of feature maps.

    sizes[i] and aspect_ratios[i] can have an arbitrary number of elements,
    and AnchorGenerator will output a set of sizes[i] * aspect_ratios[i] anchors
    per spatial location for feature map i.

    Args:
        sizes (Tuple[Tuple[int]]):
        aspect_ratios (Tuple[Tuple[float]]):
    cell_anchorsc                 X   t         |           t        |d   t        t        f      st	        d |D              }t        |d   t        t        f      s|ft        |      z  }|| _        || _        t        ||      D cg c]  \  }}| j                  ||       c}}| _
        y c c}}w )Nr   c              3   "   K   | ]  }|f 	 y wN ).0ss     e/var/www/teggl/fontify/venv/lib/python3.12/site-packages/torchvision/models/detection/anchor_utils.py	<genexpr>z+AnchorGenerator.__init__.<locals>.<genexpr>,   s     .11$.s   )super__init__
isinstancelisttuplelensizesaspect_ratioszipgenerate_anchorsr   )selfr   r   sizeaspect_ratio	__class__s        r   r   zAnchorGenerator.__init__#   s    
 	%(T5M2...E-*T5M:*,s5z9M
*PSTY[hPi
:L$D!!$5
 
s    B&cpuscalesr   dtypedevicereturnc                 ~   t        j                  |||      }t        j                  |||      }t        j                  |      }d|z  }|d d d f   |d d d f   z  j                  d      }|d d d f   |d d d f   z  j                  d      }t        j                  | | ||gd      dz  }	|	j                         S )Nr$   r%   r   dim   )torch	as_tensorsqrtviewstackround)
r   r#   r   r$   r%   h_ratiosw_ratioswshsbase_anchorss
             r   r   z AnchorGenerator.generate_anchors:   s     uVDU6R::m,x<q$w&q/177;q$w&q/177;{{RC"b"#51=A!!##    c                 n    | j                   D cg c]  }|j                  ||       c}| _         y c c}w )Nr(   )r   to)r   r$   r%   cell_anchors       r   set_cell_anchorsz AnchorGenerator.set_cell_anchorsL   s+    [_[l[lmK[^^%^Gmms   2c                     t        | j                  | j                        D cg c]  \  }}t        |      t        |      z   c}}S c c}}w r   )r   r   r   r   )r   r   as      r   num_anchors_per_locationz(AnchorGenerator.num_anchors_per_locationO   s7    ,/

D<N<N,OPDAqAQPPPs   !A	
grid_sizesstridesc           	         g }| j                   }t        j                  |d ud       t        j                  t        |      t        |      cxk(  xr t        |      k(  nc d       t	        |||      D ]  \  }}}|\  }}	|\  }
}|j
                  }t        j                  d|	t        j                  |      |z  }t        j                  d|t        j                  |      |
z  }t        j                  ||d      \  }}|j                  d      }|j                  d      }t        j                  ||||fd	      }|j                  |j                  ddd
      |j                  ddd
      z   j                  dd
              |S )Nzcell_anchors should not be NonezAnchors should be Tuple[Tuple[int]] because each feature map could potentially have different sizes and aspect ratios. There needs to be a match between the number of feature maps passed and the number of sizes / aspect ratios specified.r   r(   ijindexingr)   r   r*      )r   r-   _assertr   r   r%   arangeint32meshgridreshaper1   appendr0   )r   r@   rA   anchorsr   r   strider7   grid_height
grid_widthstride_heightstride_widthr%   shifts_xshifts_yshift_yshift_xshiftss                     r   grid_anchorszAnchorGenerator.grid_anchorsT   sc   ((l$.0QR
Os7|@s</@@U	
 +.j'<*P 	a&D&,&*#K*0'M<!((F ||AzVTWccH||A{%++fUXeeH$~~h4PGWoob)Goob)G[['7GW!E1MF NNFKKAq1L4E4EaQ4OOXXY[]^_`	a" r8   
image_listfeature_mapsc           	         |D cg c]  }|j                   dd   }}|j                  j                   dd  }|d   j                  |d   j                  }}|D cg c]~  }t	        j
                  dt        j                  |      j                  |d   |d   z        t	        j
                  dt        j                  |      j                  |d   |d   z        g }	}| j                  ||       | j                  ||	      }
g }t        t        |j                              D ]"  }|
D cg c]  }| }}|j                  |       $ |D cg c]  }t	        j                  |       }}|S c c}w c c}w c c}w c c}w )Nr   r   r(   r   )shapetensorsr$   r%   r-   emptyint64fill_r<   rX   ranger   image_sizesrL   cat)r   rY   rZ   feature_mapr@   
image_sizer$   r%   grA   anchors_over_all_feature_mapsrM   _anchors_per_feature_mapanchors_in_imageanchors_per_images                   r   forwardzAnchorGenerator.forwards   s   @LMk'',M
M''--bc2
$Q--|A/E/Ev  

  Bekk&AGG
STYZ[\Y]H]^Bekk&AGG
STYZ[\Y]H]^
 
 	eV,(,(9(9*g(N%,.s:1123 	-AWtu<S 7uuNN+,	- JQQ4E599./QQ# N
  vQs   E*BE/(	E4
E9)))      i   ))      ?      ?g       @)__name__
__module____qualname____doc__r   r-   r   __annotations__r   float32r%   intfloatr$   r   r<   r?   rX   r   rm   __classcell__r!   s   @r   r
   r
   
   s   * 	U\\*O !(
6 #]]+u||E2$S	$ E{$ {{	$
 $ 
$$nekk n5<< nQ$s) Q
tDI d6lAS X\]cXd >) 4< DQWL r8   r
   c                       e Zd ZdZ	 	 	 	 	 ddeee      dededeee      deee      def fdZ	e
j                   e
j                  d	      fd
ede
j                  de
j                  dee   fdZdee   fdZe
j                  fdeee      dee   de
j                  defdZdefdZdedee   dee   fdZ xZS )DefaultBoxGeneratora  
    This module generates the default boxes of SSD for a set of feature maps and image sizes.

    Args:
        aspect_ratios (List[List[int]]): A list with all the aspect ratios used in each feature map.
        min_ratio (float): The minimum scale :math:`	ext{s}_{	ext{min}}` of the default boxes used in the estimation
            of the scales of each feature map. It is used only if the ``scales`` parameter is not provided.
        max_ratio (float): The maximum scale :math:`	ext{s}_{	ext{max}}`  of the default boxes used in the estimation
            of the scales of each feature map. It is used only if the ``scales`` parameter is not provided.
        scales (List[float]], optional): The scales of the default boxes. If not provided it will be estimated using
            the ``min_ratio`` and ``max_ratio`` parameters.
        steps (List[int]], optional): It's a hyper-parameter that affects the tiling of default boxes. If not provided
            it will be estimated from the data.
        clip (bool): Whether the standardized values of default boxes should be clipped between 0 and 1. The clipping
            is applied while the boxes are encoded in format ``(cx, cy, w, h)``.
    r   	min_ratio	max_ratior#   stepsclipc                    t         
|           |"t        |      t        |      k7  rt        d      || _        || _        || _        t        |      }|Z|dkD  rK||z
  }t        |      D 	cg c]  }	|||	z  |dz
  z  z    c}	| _        | j                  j                  d       n||g| _        n|| _        | j                  |      | _        y c c}	w )Nz3aspect_ratios and steps should have the same lengthr   rq   )r   r   r   
ValueErrorr   r   r   rb   r#   rL   _generate_wh_pairs	_wh_pairs)r   r   r~   r   r#   r   r   num_outputsrange_ratiokr!   s             r   r   zDefaultBoxGenerator.__init__   s     	]!3s5z!ARSS*
	-( >Q')3Z_`kZlmUVy;?kC>O+PPm""3'()4 DK00= ns   -Cr"   r   r$   r%   r&   c                    g }t        |      D ]  }| j                  |   }t        j                  | j                  |   | j                  |dz      z        }||g||gg}| j                  |   D ]R  }	t        j                  |	      }
| j                  |   |
z  }| j                  |   |
z  }|j                  ||g||gg       T |j                  t        j                  |||              |S )Nr   r(   )	rb   r#   mathr/   r   extendrL   r-   r.   )r   r   r$   r%   r   r   s_k	s_prime_kwh_pairsarsq_arwhs                r   r   z&DefaultBoxGenerator._generate_wh_pairs   s     #%	{# 	TA++a.C		$++a.4;;q1u3E"EFIc
Y	$:;H ((+ 2		"KKNU*KKNU*!Q!Q 01	2 U__XU6RS	T r8   c                 ^    | j                   D cg c]  }ddt        |      z  z    c}S c c}w )Nr,   )r   r   )r   rs     r   r?   z,DefaultBoxGenerator.num_anchors_per_location   s(    (,(:(:;1AAJ;;;s   *r@   rf   c                    g }t        |      D ]  \  }}| j                  +|d   | j                  |   z  }|d   | j                  |   z  }n|\  }}t        j                  d|d         dz   |z  j	                  |      }	t        j                  d|d         dz   |z  j	                  |      }
t        j
                  |
|	d      \  }}|j                  d      }|j                  d      }t        j                  ||ft        | j                  |         z  d      j                  dd	      }| j                  r | j                  |   j                  dd
      n| j                  |   }|j                  |d   |d   z  d      }t        j                  ||fd      }|j                  |        t        j                  |d      S )Nr   r   rp   r$   rC   rD   r)   r*   r,   )minmax)	enumerater   r-   rH   r:   rJ   rK   r1   r   r   r   clamprepeatrd   rL   )r   r@   rf   r$   default_boxesr   f_kx_f_ky_f_krS   rT   rU   rV   rW   _wh_pairr   default_boxs                    r   _grid_default_boxesz'DefaultBoxGenerator._grid_default_boxes   s    
+ 	.FAszz%"1

15"1

15"uaQ036%?CC%CPHaQ036%?CC%CPH$~~h4PGWoob)Goob)G[['7!3c$..:K6L!LRTU]]^`bcdF@D		t~~a(..1!.<t~~^_O`HAQ!<H))VX$6A>K  -+	.. yyA..r8   c           
          | j                   j                   d| j                   d| j                   d| j                   d| j
                   d
}|S )Nz(aspect_ratios=z, clip=z	, scales=z, steps=))r!   rr   r   r   r#   r   )r   r   s     r   __repr__zDefaultBoxGenerator.__repr__   sX    ~~&&' (!//0dii[}tzzl 	
 r8   rY   rZ   c           
      :   |D cg c]  }|j                   dd   }}|j                  j                   dd  }|d   j                  |d   j                  }}| j	                  |||      }|j                  |      }g }	t        j                  |d   |d   g|j                        }
|j                  D ]c  }|}t        j                  |d d d df   d|d d dd f   z  z
  |
z  |d d d df   d|d d dd f   z  z   |
z  gd      }|	j                  |       e |	S c c}w )	Nr\   r   r   r   )r%   r,   rp   r)   )r]   r^   r$   r%   r   r:   r-   tensorrc   rd   rL   )r   rY   rZ   re   r@   rf   r$   r%   r   dboxesx_y_sizeri   dboxes_in_images                r   rm   zDefaultBoxGenerator.forward   sG   @LMk'',M
M''--bc2
$Q--|A/E/Ev00Zu0U%((0<<A
1 >}G[G[\'' 		+A+O#ii$QU+cOAqrE4J.JJhV$QU+cOAqrE4J.JJhV O MM/*		+ % Ns   D)g333333?g?NNT)rr   rs   rt   ru   r   rx   ry   r   boolr   r-   rw   r%   r$   r   r   r?   r   strr   r   rm   rz   r{   s   @r   r}   r}      s?   (  (,%)>DI> > 	>
 e%> S	"> >> 6;]][g[`[g[ghm[n',{{LQLL	f(<$s) < X]WdWd/tCy//7;Cy/IN/	/:	# 	) 4< DQWL r8   r}   )r   typingr   r   r-   r   r   rY   r   Moduler
   r}   r   r8   r   <module>r      s9     !   !{bii {|D")) Dr8   