
    %`iM.                         d dl Z d dl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
dS )
    N)Optional)nnTensor   )	ImageListc                   r    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_anchors)      i   )      ?      ?g       @c                     t                                                       t          |d         t          t          f          st	          d |D                       }t          |d         t          t          f          s|ft          |          z  }| _        | _         fdt          ||          D              _	        d S )Nr   c              3      K   | ]}|fV  d S )N ).0ss     }/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/torchvision/models/detection/anchor_utils.py	<genexpr>z+AnchorGenerator.__init__.<locals>.<genexpr>,   s$      ..11$......    c                 B    g | ]\  }}                     ||          S r   )generate_anchors)r   sizeaspect_ratioselfs      r   
<listcomp>z,AnchorGenerator.__init__.<locals>.<listcomp>2   s:     
 
 
:L$D!!$55
 
 
r   )
super__init__
isinstancelisttuplelensizesaspect_ratioszipr
   )r   r%   r&   	__class__s   `  r   r    zAnchorGenerator.__init__#   s    
 	%(T5M22 	/.......E-*T5M:: 	:*,s5zz9M
*
 
 
 
PSTY[hPiPi
 
 
r   cpuscalesr&   dtypedevicereturnc                    t          j        |||          }t          j        |||          }t          j        |          }d|z  }|d d d f         |d d d f         z                      d          }|d d d f         |d d d f         z                      d          }t          j        | | ||gd          dz  }	|	                                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DDU6RRR:m,,x<qqq$w&qqq/177;;qqq$w&qqq/177;;{RC"b"#51===A!!###r   c                 <    fd| j         D             | _         d S )Nc                 >    g | ]}|                                S )r/   )to)r   cell_anchorr,   r+   s     r   r   z4AnchorGenerator.set_cell_anchors.<locals>.<listcomp>M   s)    mmmK[^^%^GGmmmr   )r
   )r   r+   r,   s    ``r   set_cell_anchorsz AnchorGenerator.set_cell_anchorsL   s-    mmmmm[_[lmmmr   c                 J    d t          | j        | j                  D             S )Nc                 R    g | ]$\  }}t          |          t          |          z  %S r   r$   )r   r   as      r   r   z<AnchorGenerator.num_anchors_per_location.<locals>.<listcomp>P   s,    PPPDAqAQPPPr   )r'   r%   r&   r   s    r   num_anchors_per_locationz(AnchorGenerator.num_anchors_per_locationO   s%    PPC
D<N,O,OPPPPr   
grid_sizesstridesc           	      ,   g }| j         }t          j        |d ud           t          j        t          |          t          |          cxk    ot          |          k    nc d           t	          |||          D ]\  }}}|\  }}	|\  }
}|j        }t          j        d|	t          j        |          |z  }t          j        d|t          j        |          |
z  }t          j        ||d          \  }}|	                    d          }|	                    d          }t          j
        ||||fd	          }|                    |                    ddd
          |                    ddd
          z   	                    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indexingr0   r   r1      )r
   r4   _assertr$   r'   r,   arangeint32meshgridreshaper8   appendr7   )r   rJ   rK   anchorsr
   r   strider>   grid_height
grid_widthstride_heightstride_widthr,   shifts_xshifts_yshift_yshift_xshiftss                     r   grid_anchorszAnchorGenerator.grid_anchorsT   s   (l$.0QRRR
OOs7||@@@@s</@/@@@@@U	
 	
 	
 +.j'<*P*P 	a 	a&D&,&*#K*0'M<!(F |AzVTTTWccH|A{%+fUUUXeeH$~h4PPPGWoob))Goob))G['7GW!E1MMMF NNFKKAq11L4E4EaQ4O4OOXXY[]^__````r   
image_listfeature_mapsc                   
 d |D             }|j         j        dd          |d         j        |d         j        c}

fd|D             }|                     |
           |                     ||          }g }t          t          |j                            D ]#}d |D             }	|	                    |	           $d |D             }|S )Nc                 ,    g | ]}|j         d d         S Nshaper   feature_maps     r   r   z+AnchorGenerator.forward.<locals>.<listcomp>t   $    MMMk',MMMr   rh   r   c                    g | ]}t          j        d t           j                                      d         |d         z            t          j        d t           j                                      d         |d         z            gS )r   r/   r   r   )r4   emptyint64fill_)r   gr,   
image_sizes     r   r   z+AnchorGenerator.forward.<locals>.<listcomp>w   s     
 
 

  Bek&AAAGG
STYZ[\Y]H]^^Bek&AAAGG
STYZ[\Y]H]^^
 
 
r   c                     g | ]}|S r   r   )r   anchors_per_feature_maps     r   r   z+AnchorGenerator.forward.<locals>.<listcomp>   s    uuu<S 7uuur   c                 6    g | ]}t          j        |          S r   )r4   cat)r   anchors_per_images     r   r   z+AnchorGenerator.forward.<locals>.<listcomp>   s$    QQQ4E59.//QQQr   )
tensorsrj   r+   r,   rC   rb   ranger$   image_sizesrV   )r   rc   rd   rJ   r+   rK   anchors_over_all_feature_mapsrW   _anchors_in_imager,   rs   s             @@r   forwardzAnchorGenerator.forwards   s   MMMMM
'-bcc2
$Q-|A/Ev
 
 
 
 

  
 
 
 	eV,,,(,(9(9*g(N(N%,.s:12233 	- 	-AuuWtuuuNN+,,,,QQQQQr   )r   r   )__name__
__module____qualname____doc__r"   r4   r   __annotations__r    float32r,   intfloatr+   r   rC   rI   rb   r   r   __classcell__r(   s   @r   r	   r	   
   s        * 	U\*O !(
 
 
 
 
 
6 #]+u|E22$ $S	$ E{$ {	$
 $ 
$ $ $ $$nek n5< n n n nQ$s) Q Q Q Q
tDI d6lAS X\]cXd    >) 4< DQWL        r   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)``.
    333333??NTr&   	min_ratio	max_ratior*   stepsclipc                    t                                                       |/t          |          t          |          k    rt          d          || _        || _        || _        t          |          |Rdk    rB|z
  fdt                    D             | _        | j        	                    d           n|g| _        n|| _        | 
                              | _        d S )Nz3aspect_ratios and steps should have the same lengthr   c                 ,    g | ]}|z  d z
  z  z   S )r   r   )r   kr   num_outputsrange_ratios     r   r   z0DefaultBoxGenerator.__init__.<locals>.<listcomp>   s-    mmmUVy;?kC>O+PPmmmr   r   )r   r    r$   
ValueErrorr&   r   r   rz   r*   rV   _generate_wh_pairs	_wh_pairs)
r   r&   r   r   r*   r   r   r   r   r(   s
     `    @@r   r    zDefaultBoxGenerator.__init__   s     	]!3!3s5zz!A!ARSSS*
	-(( >Q')3mmmmmmZ_`kZlZlmmm""3''''()4 DK00==r   r)   r   r+   r,   r-   c                    g }t          |          D ]}| j        |         }t          j        | j        |         | j        |dz            z            }||g||gg}| j        |         D ]Q}	t          j        |	          }
| j        |         |
z  }| j        |         |
z  }|                    ||g||gg           R|                    t          j        |||                     |S )Nr   r/   )	rz   r*   mathr6   r&   extendrV   r4   r5   )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 	TA+a.C	$+a.4;q1u3E"EFFIc
Y	$:;H (+ 2 2	"KNU*KNU*!Q!Q 01111U_XU6RRRSSSSr   c                 $    d | j         D             S )Nc                 8    g | ]}d d t          |          z  z   S )r3   rF   )r   rs     r   r   z@DefaultBoxGenerator.num_anchors_per_location.<locals>.<listcomp>   s&    ;;;1AAJ;;;r   )r&   rH   s    r   rI   z,DefaultBoxGenerator.num_anchors_per_location   s    ;;(:;;;;r   rJ   rs   c                    g }t          |          D ]\  }}| j        -|d         | j        |         z  }|d         | j        |         z  }n|\  }}t          j        d|d                   dz   |z                      |          }	t          j        d|d                   dz   |z                      |          }
t          j        |
|	d          \  }}|                    d          }|                    d          }t          j        ||ft          | j	        |                   z  d                              dd	          }| j
        r"| j	        |                             dd
          n| j	        |         }|                    |d         |d         z  d          }t          j        ||fd          }|                    |           t          j        |d          S )Nr   r   r   r+   rM   rN   r0   r1   r3   )minmax)	enumerater   r4   rR   rA   rT   rU   r8   r$   r   r   clamprepeatrw   rV   )r   rJ   rs   r+   default_boxesr   f_kx_f_ky_f_kr]   r^   r_   r`   ra   _wh_pairr   default_boxs                    r   _grid_default_boxesz'DefaultBoxGenerator._grid_default_boxes   s    
++ 	. 	.FAsz%"1
15"1
15"uaQ0036%?CC%CPPHaQ0036%?CC%CPPH$~h4PPPGWoob))Goob))G['7!3c$.:K6L6L!LRTUUU]]^`bcddF@D	`t~a(..1!.<<<t~^_O`HAQ!<<H)VX$6A>>>K  ----yA....r   c           
      d    | j         j         d| j         d| j         d| j         d| j         d
}|S )Nz(aspect_ratios=z, clip=z	, scales=z, steps=))r(   r   r&   r   r*   r   )r   r   s     r   __repr__zDefaultBoxGenerator.__repr__   sf    ~&  !/ i    z	   	
 r   rc   rd   c           
         d |D             }|j         j        dd          }|d         j        |d         j        }}|                     |||          }|                    |          }g }t          j        |d         |d         g|j                  }	|j        D ]r}
|}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	          }|
                    |           s|S )
Nc                 ,    g | ]}|j         d d         S rg   ri   rk   s     r   r   z/DefaultBoxGenerator.forward.<locals>.<listcomp>   rm   r   rh   r   r   r   )r,   r3   r   r0   )ry   rj   r+   r,   r   rA   r4   tensorr{   rw   rV   )r   rc   rd   rJ   rs   r+   r,   r   dboxesx_y_sizer}   dboxes_in_images               r   r   zDefaultBoxGenerator.forward   sL   MMMMM
'-bcc2
$Q-|A/Ev00Zu0UU%((00<A
1 >}G[\\\' 		+ 		+A+O#i$QQQU+cOAAAqrrE4J.JJhV$QQQU+cOAAAqrrE4J.JJhV  O MM/****r   )r   r   NNT)r   r   r   r   r"   r   r   r   boolr    r4   r   r,   r+   r   r   rI   r   strr   r   r   r   r   s   @r   r   r      s        (  (,%)> >DI> > 	>
 e%> S	"> > > > > > >> 6;][g[`[ghm[n[n ',{LQL	f   (<$s) < < < < X]Wd/ /tCy//7;Cy/IN/	/ / / /:	# 	 	 	 	) 4< DQWL        r   r   )r   typingr   r4   r   r   rc   r   Moduler	   r   r   r   r   <module>r      s                    ! ! ! ! ! !{ { { { {bi { { {|D D D D D") D D D D Dr   