
    .h                     B    d dl mZ d dlmZ d dlmZmZ  G d de      Zy)    )BasePredictor)Results)nmsopsc                   (    e Zd ZdZd Zd Zd Zd Zy)DetectionPredictora:  
    A class extending the BasePredictor class for prediction based on a detection model.

    This predictor specializes in object detection tasks, processing model outputs into meaningful detection results
    with bounding boxes and class predictions.

    Attributes:
        args (namespace): Configuration arguments for the predictor.
        model (nn.Module): The detection model used for inference.
        batch (list): Batch of images and metadata for processing.

    Methods:
        postprocess: Process raw model predictions into detection results.
        construct_results: Build Results objects from processed predictions.
        construct_result: Create a single Result object from a prediction.
        get_obj_feats: Extract object features from the feature maps.

    Examples:
        >>> from ultralytics.utils import ASSETS
        >>> from ultralytics.models.yolo.detect import DetectionPredictor
        >>> args = dict(model="yolo11n.pt", source=ASSETS)
        >>> predictor = DetectionPredictor(overrides=args)
        >>> predictor.predict_cli()
    c                    t        | dd      du}t        j                  || j                  j                  | j                  j
                  | j                  j                  | j                  j                  | j                  j                  | j                  j                  dk(  rdnt        | j                  j                        t        | j                  dd      | j                  j                  dk(  |
      }t        |t              st        j                   |      }|r$| j#                  | j$                  |d	         }|d   } | j&                  |||fi |}|rt)        |      D ]  \  }}	|	|_         |S )
ay  
        Post-process predictions and return a list of Results objects.

        This method applies non-maximum suppression to raw model predictions and prepares them for visualization and
        further analysis.

        Args:
            preds (torch.Tensor): Raw predictions from the model.
            img (torch.Tensor): Processed input image tensor in model input format.
            orig_imgs (torch.Tensor | list): Original input images before preprocessing.
            **kwargs (Any): Additional keyword arguments.

        Returns:
            (list): List of Results objects containing the post-processed predictions.

        Examples:
            >>> predictor = DetectionPredictor(overrides=dict(model="yolo11n.pt"))
            >>> results = predictor.predict("path/to/image.jpg")
            >>> processed_results = predictor.postprocess(preds, img, orig_imgs)
        _featsNdetectr   end2endFobb)max_detncr   rotatedreturn_idxs   )getattrr   non_max_suppressionargsconfiouclassesagnostic_nmsr   tasklenmodelnames
isinstancelistr   convert_torch2numpy_batchget_obj_featsr
   construct_resultszipfeats)
selfpredsimg	orig_imgskwargs
save_feats	obj_featsresultsrfs
             d/var/www/html/ai-service/venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/predict.pypostprocesszDetectionPredictor.postprocess"   s5   * T8T2$>
''IINNIIMMIIII""II%%IINNh.qC

8H8H4IDJJ	59IINNe+"
 )T*55i@I**4;;aAI!HE($((YI&IGY/ 1     c                    ddl }t        d |D              }|j                  |D cg c]U  }|j                  dddd      j	                  |j
                  d   d||j
                  d   |z        j                  d      W c}d      }t        ||      D cg c]  \  }}|j
                  d   r||   ng  c}}S c c}w c c}}w )	z.Extract object features from the feature maps.r   Nc              3   :   K   | ]  }|j                   d      yw)r   N)shape).0xs     r/   	<genexpr>z3DetectionPredictor.get_obj_feats.<locals>.<genexpr>X   s     .q
.s         r   )dim)torchmincatpermutereshaper4   meanr#   )	r%   	feat_mapsidxsr<   sr6   r+   r$   idxs	            r/   r!   z DetectionPredictor.get_obj_featsT   s    .I..IIeno`aQYYq!Q"**1771:r1aggajAoNSSXZS[ouv  
	 FITXEYZzucciilc
2ZZ pZs   AB< Cc                     t        ||| j                  d         D cg c]  \  }}}| j                  ||||       c}}}S c c}}}w )a  
        Construct a list of Results objects from model predictions.

        Args:
            preds (list[torch.Tensor]): List of predicted bounding boxes and scores for each image.
            img (torch.Tensor): Batch of preprocessed images used for inference.
            orig_imgs (list[np.ndarray]): List of original images before preprocessing.

        Returns:
            (list[Results]): List of Results objects containing detection information for each image.
        r   )r#   batchconstruct_result)r%   r&   r'   r(   predorig_imgimg_paths          r/   r"   z$DetectionPredictor.construct_results^   sQ     -0y$**Q-,P
 
(h !!$Xx@
 	
 
s   Ac           	          t        j                  |j                  dd |ddddf   |j                        |ddddf<   t        ||| j                  j
                  |ddddf         S )a.  
        Construct a single Results object from one image prediction.

        Args:
            pred (torch.Tensor): Predicted boxes and scores with shape (N, 6) where N is the number of detections.
            img (torch.Tensor): Preprocessed image tensor used for inference.
            orig_img (np.ndarray): Original image before preprocessing.
            img_path (str): Path to the original image file.

        Returns:
            (Results): Results object containing the original image, image path, class names, and scaled bounding boxes.
        r8   N      )pathr   boxes)r   scale_boxesr4   r   r   r   )r%   rI   r'   rJ   rK   s        r/   rH   z#DetectionPredictor.construct_resulto   sh     oociimT!RaR%[(..QQUxhdjj6F6FdSTVXWXVXSXkZZr1   N)__name__
__module____qualname____doc__r0   r!   r"   rH    r1   r/   r   r      s    20d[
"[r1   r   N)ultralytics.engine.predictorr   ultralytics.engine.resultsr   ultralytics.utilsr   r   r   rV   r1   r/   <module>rZ      s     7 . &u[ u[r1   