
    .hQ7                         d dl Z d dlZd dlZd dlmZ d dlmZmZ d dlm	Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dde
de
deded	ed
ede
dededededefdZ G d d      Zy)    N)LOGGER)batch_probioubox_iou)	xywh2xyxy
conf_thres	iou_thresagnosticmulti_labelmax_detncmax_time_imgmax_nmsmax_whrotatedend2endreturn_idxsc           	      
   d|cxk  rdk  sn J d| d       d|cxk  rdk  sn J d| d       t        | t        t        f      r| d   } |!t        j                  || j
                        }| j                  d   d	k(  s|rP| D cg c]  }||ddd
f   |kD     d|  }}|-|D cg c]"  }||dddd	f   |k(  j                  d         $ }}|S | j                  d   }|xs | j                  d   d
z
  }| j                  d   |z
  d
z
  }d
|z   }| ddd
|f   j                  d      |kD  }t        j                  | j                  d   | j
                        j                  |d      d   }d|	|z  z   }||dkD  z  }| j                  dd      } |st        | ddd
f         | ddd
f<   t        j                         }t        j                  dd	|z   f| j
                        g|z  }t        j                  d| j
                        g|z  }t        t!        | |            D ]D  \  }\  }}||   }||   }|r||   }|rt#        ||         r|s||   }t        j                  t#        |      ||z   d
z   f|j
                        }t        |ddddf         |dddd
f<   d|t%        t#        |            |dddf   j'                         d
z   f<   t        j(                  ||fd      }|j                  d   s|j+                  d
||fd      \  }} }!|rat        j,                  | |kD        \  }"}#t        j(                  ||"   ||"d
|#z   df   |#dddf   j/                         |!|"   fd      }|rb||"   }n\| j1                  dd      \  }$}#|$j3                  d      |kD  }t        j(                  ||$|#j/                         |!fd      |   }|r||   }|)|dddd	f   |k(  j                  d      }||   }|r||   }|j                  d   }%|%s|%|
kD  r(|ddd
f   j5                  d      d|
 }||   }|r||   }|dddd	f   |rdn|z  }&|ddd
f   }'|rVt        j(                  |ddddf   |&z   |dddd
f   |ddddf   fd      }(t6        j9                  |(|'|t:              }"nY|dddd
f   |&z   }(dt<        j>                  v r"ddl })|)jB                  jE                  |(|'|      }"nt6        jE                  |(|'|      }"|"d| }"||"   ||<   |r||"   j3                  d      ||<   t        j                         |z
  |kD  s+tG        jH                  d|dd        n |r||fS |S c c}w c c}w )a8  
    Perform non-maximum suppression (NMS) on prediction results.

    Applies NMS to filter overlapping bounding boxes based on confidence and IoU thresholds. Supports multiple
    detection formats including standard boxes, rotated boxes, and masks.

    Args:
        prediction (torch.Tensor): Predictions with shape (batch_size, num_classes + 4 + num_masks, num_boxes)
            containing boxes, classes, and optional masks.
        conf_thres (float): Confidence threshold for filtering detections. Valid values are between 0.0 and 1.0.
        iou_thres (float): IoU threshold for NMS filtering. Valid values are between 0.0 and 1.0.
        classes (list[int], optional): List of class indices to consider. If None, all classes are considered.
        agnostic (bool): Whether to perform class-agnostic NMS.
        multi_label (bool): Whether each box can have multiple labels.
        labels (list[list[Union[int, float, torch.Tensor]]]): A priori labels for each image.
        max_det (int): Maximum number of detections to keep per image.
        nc (int): Number of classes. Indices after this are considered masks.
        max_time_img (float): Maximum time in seconds for processing one image.
        max_nms (int): Maximum number of boxes for NMS.
        max_wh (int): Maximum box width and height in pixels.
        rotated (bool): Whether to handle Oriented Bounding Boxes (OBB).
        end2end (bool): Whether the model is end-to-end and doesn't require NMS.
        return_idxs (bool): Whether to return the indices of kept detections.

    Returns:
        output (list[torch.Tensor]): List of detections per image with shape (num_boxes, 6 + num_masks)
            containing (x1, y1, x2, y2, confidence, class, mask1, mask2, ...).
        keepi (list[torch.Tensor]): Indices of kept detections if return_idxs=True.
    r      zInvalid Confidence threshold z&, valid values are between 0.0 and 1.0zInvalid IoU Ndevice         ).Ng       @.)r   r   g      ?T)keepdim
descending   )dim)iou_functorchvisionzNMS time limit z.3fz
s exceeded)%
isinstancelisttupletorchtensorr   shapeanyamaxarangeexpand	transposer   timezeros	enumerateziplenrangelongcatsplitwherefloatmaxviewargsortTorchNMSfast_nmsr   sysmodulesr"   opsnmsr   warning)*
predictionr   r   classesr	   r
   labelsr   r   r   r   r   r   r   r   predoutputbsextramixcxinds
time_limittkeepixixxkfiltlbvboxclsmaskijconfncscoresboxesr"   s*                                             S/var/www/html/ai-service/venv/lib/python3.12/site-packages/ultralytics/utils/nms.pynon_max_suppressionra      s   ^ 
as#@Lr!ss	Q`,yk9_ ``*tUm,]
,,wz/@/@Aq GFPQd$tAqDzJ./9QQIOPdDAaCLG388;<PFP			!	B		(
  #a'BQ"$q(E	
RB	AqtG		!	!!	$z	1BLL))"-j6G6GHOOPRTVWXabE |b((J26K%%b"-J'
37(;<
37		Akk1a%i.1B1BCDrIF[[
(9(9:;b@E Z!78 IGQ "vdGDB c&*ogBSWb5j1n5ahhGA AqsF,Aa!eH58AeCGnbAhmmo112		1a&!$A wwqz !R3S$;;sZ/0DAq		3q61QAt^#4a4j6F6F6H$q'RTUVAUggag.GD!99R=:-D		3aggi6:4@AX a1fI(--a0D$AX GGAJw;QT7??d?3HW=D$AXa1fIhF31a4IIqBQBx!|Qq!A#vY!RS&	BKE!!%]!SAa!eHqLE+"OO''vyALL	:hwKqTr
1

2E"IIIK!Oz)NN_Z,<JGHSIV *FE?5v5G RPs   U5('U:c                   Z   e Zd ZdZededfdej                  dej                  dede	de	dej                  fd	       Z
edej                  dej                  dedej                  fd
       Ze	 ddej                  dej                  dej                  dede	dej                  fd       Zy)r<   a  
    Ultralytics custom NMS implementation optimized for YOLO.

    This class provides static methods for performing non-maximum suppression (NMS) operations on bounding boxes,
    including both standard NMS and batched NMS for multi-class scenarios.

    Methods:
        nms: Optimized NMS with early termination that matches torchvision behavior exactly.
        batched_nms: Batched NMS for class-aware suppression.

    Examples:
        Perform standard NMS on boxes and scores
        >>> boxes = torch.tensor([[0, 0, 10, 10], [5, 5, 15, 15]])
        >>> scores = torch.tensor([0.9, 0.8])
        >>> keep = TorchNMS.nms(boxes, scores, 0.5)
    Tr_   r^   iou_thresholduse_triu
exit_earlyreturnc                 J   | j                         dk(  r2|r0t        j                  dt        j                  | j                        S t        j
                  |d      }| |   }  || |       }|rP|j                  d      }t        j                  ||k\  j                  d      dk        j                  d      }||   S | j                  d   }	t        j                  |	| j                  	      j                  dd      j                  d|	      }
t        j                  |	| j                  	      j                  dd      j                  |	d      }|
|k  }||z  }d|||k\  j                  d      dk   <   t        j                  ||j                  d         j                  }||   S )
a  
        Fast-NMS implementation from https://arxiv.org/pdf/1904.02689 using upper triangular matrix operations.

        Args:
            boxes (torch.Tensor): Bounding boxes with shape (N, 4) in xyxy format.
            scores (torch.Tensor): Confidence scores with shape (N,).
            iou_threshold (float): IoU threshold for suppression.
            use_triu (bool): Whether to use torch.triu operator for upper triangular matrix operations.
            iou_func (callable): Function to compute IoU between boxes.
            exit_early (bool): Whether to exit early if there are no boxes.

        Returns:
            (torch.Tensor): Indices of boxes to keep after NMS.

        Examples:
            Apply NMS to a set of boxes
            >>> boxes = torch.tensor([[0, 0, 10, 10], [5, 5, 15, 15]])
            >>> scores = torch.tensor([0.9, 0.8])
            >>> keep = TorchNMS.nms(boxes, scores, 0.5)
        r   r   dtyper   Tr   r   )diagonalr   r   )numelr&   emptyint64r   r;   triu_nonzerosumsqueeze_r(   r+   r:   r,   topkindices)r_   r^   rc   rd   r!   re   
sorted_idxiouspickr\   row_idxcol_idx
upper_masks                r`   r=   zTorchNMS.fast_nms   so   : ;;=A*;;t5;;u||LL]]6d;
j!u%::q:)D==$-"7!<!<Q!?1!DENNrRD $ AAll1U\\:??AFMMbRSTGll1U\\:??2FMMaQSTG 7*J*$D=>Fdm+003q89:::ffll1o6>>D$    c                    | j                         dk(  r0t        j                  dt        j                  | j                        S | j                  d      \  }}}}||z
  ||z
  z  }|j                  dd      }t        j                  |j                         t        j                  | j                        }	d}
|j                         dkD  r|d   }||	|
<   |
dz  }
|j                         dk(  rn|dd }t        j                  ||   ||         }t        j                  ||   ||         }t        j                  ||   ||         }t        j                  ||   ||         }||z
  j                  d      }||z
  j                  d      }||z  }|j                         dk(  r|}|||   ||   z   |z
  z  }|||k     }|j                         dkD  r|	d|
 S )	a  
        Optimized NMS with early termination that matches torchvision behavior exactly.

        Args:
            boxes (torch.Tensor): Bounding boxes with shape (N, 4) in xyxy format.
            scores (torch.Tensor): Confidence scores with shape (N,).
            iou_threshold (float): IoU threshold for suppression.

        Returns:
            (torch.Tensor): Indices of boxes to keep after NMS.

        Examples:
            Apply NMS to a set of boxes
            >>> boxes = torch.tensor([[0, 0, 10, 10], [5, 5, 15, 15]])
            >>> scores = torch.tensor([0.9, 0.8])
            >>> keep = TorchNMS.nms(boxes, scores, 0.5)
        r   rh   ri   r   Tr   N)min)rl   r&   rm   rn   r   unbindr;   r/   maximumminimumclamp_rq   )r_   r^   rc   x1y1x2y2areasorderkeepkeep_idxrY   restxx1yy1xx2yy2whinterious                        r`   rA   zTorchNMS.nms   s   & ;;=A;;t5;;u||LL aBBbR"W% qT2 {{5;;=ELLQkkmaaADNMH{{}!9D--1r$x0C--1r$x0C--1r$x0C--1r$x0C s""q")As""q")AEEyy{a58eDk1E9:C-.E3 kkma6 IXr{   idxsuse_fast_nmsc                 N   | j                         dk(  r0t        j                  dt        j                  | j                        S | j                         }|j                  |       |dz   z  }| |dddf   z   }|rt        j                  |||      S t        j                  |||      S )a7  
        Batched NMS for class-aware suppression.

        Args:
            boxes (torch.Tensor): Bounding boxes with shape (N, 4) in xyxy format.
            scores (torch.Tensor): Confidence scores with shape (N,).
            idxs (torch.Tensor): Class indices with shape (N,).
            iou_threshold (float): IoU threshold for suppression.
            use_fast_nms (bool): Whether to use the Fast-NMS implementation.

        Returns:
            (torch.Tensor): Indices of boxes to keep after NMS.

        Examples:
            Apply batched NMS across multiple classes
            >>> boxes = torch.tensor([[0, 0, 10, 10], [5, 5, 15, 15]])
            >>> scores = torch.tensor([0.9, 0.8])
            >>> idxs = torch.tensor([0, 1])
            >>> keep = TorchNMS.batched_nms(boxes, scores, idxs, 0.5)
        r   rh   ri   r   N)
rl   r&   rm   rn   r   r9   tor<   r=   rA   )r_   r^   r   rc   r   max_coordinateoffsetsboxes_for_nmss           r`   batched_nmszTorchNMS.batched_nms,  s    8 ;;=A;;t5;;u||LL ''%.NQ$674 00  mV]C	
 mV]C	
r{   N)F)__name__
__module____qualname____doc__staticmethodr   r&   Tensorr8   boolr=   rA   r    r{   r`   r<   r<      s   " 
 0 ||0 0  0  	0  0  
0  0 d :5<< : :e :PUP\P\ : :x  #'
||'
'
 ll'
 	'

 '
 
'
 '
r{   r<   )g      ?g?NFFr   i,  r   g?i0u  i   FFF)r>   r.   r&   ultralytics.utilsr   ultralytics.utils.metricsr   r   ultralytics.utils.opsr   r8   r   intra   r<   r   r{   r`   <module>r      s       $ < +
 Z6Z6 Z6
 Z6 Z6 Z6 	Z6 Z6 Z6 Z6 Z6 Z6 Z6zj
 j
r{   