a
    yf:9                     @   s   d Z ddlZddlZddlmZ ddlZddlZddlm	Z	m
Z
 ddlmZmZ ddlmZ ddlmZmZmZmZmZ ddlmZ dd	lmZ dd
lmZmZmZ G dd dZdS )a  
Check a model's accuracy on a test or val split of a dataset.

Usage:
    $ yolo mode=val model=yolov8n.pt data=coco8.yaml imgsz=640

Usage - formats:
    $ yolo mode=val model=yolov8n.pt                 # PyTorch
                          yolov8n.torchscript        # TorchScript
                          yolov8n.onnx               # ONNX Runtime or OpenCV DNN with dnn=True
                          yolov8n_openvino_model     # OpenVINO
                          yolov8n.engine             # TensorRT
                          yolov8n.mlpackage          # CoreML (macOS-only)
                          yolov8n_saved_model        # TensorFlow SavedModel
                          yolov8n.pb                 # TensorFlow GraphDef
                          yolov8n.tflite             # TensorFlow Lite
                          yolov8n_edgetpu.tflite     # TensorFlow Edge TPU
                          yolov8n_paddle_model       # PaddlePaddle
                          yolov8n_ncnn_model         # NCNN
    N)Path)get_cfgget_save_dir)check_cls_datasetcheck_det_dataset)AutoBackend)LOGGERTQDM	callbackscolorstremojis)check_imgsz)Profile)de_parallelselect_devicesmart_inference_modec                   @   s   e Zd ZdZd1ddZe d2ddZd3dd	Zed
ddZ	ed
ddZ
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zed%d& Zd4d'd(Zd)d* Zd+d, Zd-d. Zd/d0 ZdS )5BaseValidatora   
    BaseValidator.

    A base class for creating validators.

    Attributes:
        args (SimpleNamespace): Configuration for the validator.
        dataloader (DataLoader): Dataloader to use for validation.
        pbar (tqdm): Progress bar to update during validation.
        model (nn.Module): Model to validate.
        data (dict): Data dictionary.
        device (torch.device): Device to use for validation.
        batch_i (int): Current batch index.
        training (bool): Whether the model is in training mode.
        names (dict): Class names.
        seen: Records the number of images seen so far during validation.
        stats: Placeholder for statistics during validation.
        confusion_matrix: Placeholder for a confusion matrix.
        nc: Number of classes.
        iouv: (torch.Tensor): IoU thresholds from 0.50 to 0.95 in spaces of 0.05.
        jdict (dict): Dictionary to store JSON validation results.
        speed (dict): Dictionary with keys 'preprocess', 'inference', 'loss', 'postprocess' and their respective
                      batch processing times in milliseconds.
        save_dir (Path): Directory to save results.
        plots (dict): Dictionary to store plots for visualization.
        callbacks (dict): Dictionary to store various callback functions.
    Nc                 C   s   t |d| _|| _|| _d| _d| _d| _d| _d| _d| _	d| _
d| _d| _d| _d| _d| _ddddd| _|p|t| j| _| jjr| jd n| jjddd | jjdu rd| j_t| jjd	d
| j_i | _|pt | _dS )a  
        Initializes a BaseValidator instance.

        Args:
            dataloader (torch.utils.data.DataLoader): Dataloader to be used for validation.
            save_dir (Path, optional): Directory to save results.
            pbar (tqdm.tqdm): Progress bar for displaying progress.
            args (SimpleNamespace): Configuration for the validator.
            _callbacks (dict): Dictionary to store various callback functions.
        )Z	overridesNTg        )
preprocessZ	inferencelosspostprocesslabels)parentsexist_okgMbP?   )Zmax_dim)r   args
dataloaderpbarstridedatadevicebatch_itrainingnamesseenstatsZconfusion_matrixnciouvjdictspeedr   save_dirZsave_txtmkdirconfr   imgszplotsr
   Zget_default_callbacks)selfr   r)   r   r   
_callbacks r0   X/var/www/html/django/DPS/env/lib/python3.9/site-packages/ultralytics/engine/validator.py__init__D   s.    "zBaseValidator.__init__c                    s  |du _  jjo j  } j r|j _|j _ jjdko@|j j_|jjpR|j	} jjrd| n|
 }tj|j|jd _ j j|jjp|j|jd kM  _|  nt  t|pƈ jj	t jj jj jj jj jjd}|j _|j j_|j|j|j|jf\}}}}t  jj!|d}|r>|j" j_nJ|s|s|j#$dd j_t%&d jj d	 jj d
| d| d	 t' jj(dd dv rt) jj _nH jj*dkrt+ jj jj(d _n"t,t-d jj d jj* d jjdv rd j_.|s d j_/|j _ j0pJ 1 j$ jj( jj _0|  |j2|rddn jjd||fd  3d t4 jdt4 jdt4 jdt4 jdf}	t5 j0 6 t7 j0d}
 8t9| g  _:t;|
D ]L\}} 3d | _<|	d   =|}W d   n1 s(0    Y  |	d   ||d |d}W d   n1 sb0    Y  |	d 2  j r  j|||d 7  _W d   n1 s0    Y  |	d   >|}W d   n1 s0    Y   ?||  jjr&|dk r& @||  A|||  3d  q B } C| tDtE jFG  fd!d"|	D  _F H   I   3d#  j r|
  i ||jJ jK t7 j0 d$d%}d&d' |L D S t%&d(jMtN jFO    jjPrZ j:rZtQt' jRd) d*2}t%&d+|jS d, tTU j:| W d   n1 sF0    Y   V|} jjsn jjPrt%&d-tWd. jR  |S dS )/z_Executes validation process, running inference on dataloader and computing performance metrics.Ncpu)r   r   )weightsr   dnnr   fp16)r   batchzSetting batch=z input of shape (z, 3, z, ).>   ZymlyamlZclassify)splitz	Dataset 'z' for task=u    not found ❌>   r3   Zmpsr   F   )r,   Zon_val_start)desctotalZon_val_batch_startZimg)augment   Zon_val_batch_endc                 3   s$   | ]}|j t jj d  V  qdS )g     @@N)tlenr   Zdataset).0xr.   r0   r1   	<genexpr>       z)BaseValidator.__call__.<locals>.<genexpr>Z
on_val_endval)prefixc                 S   s    i | ]\}}|t t|d qS )   )roundfloat)rD   kvr0   r0   r1   
<dictcomp>   rH   z*BaseValidator.__call__.<locals>.<dictcomp>z]Speed: {:.1f}ms preprocess, {:.1f}ms inference, {:.1f}ms loss, {:.1f}ms postprocess per imagezpredictions.jsonwzSaving z...zResults saved to bold)Xr!   r   r@   r   r   typeampZhalfZemamodelrM   torchZ
zeros_likeZ
loss_itemsr   r-   ZstopperZpossible_stopepochZepochsevalr
   Zadd_integration_callbacksr   r   r7   r5   r6   r   ptjitenginer   r,   
batch_sizemetadatagetr   infostrr<   r   taskr   FileNotFoundErrorr   workersrectr   get_dataloaderZwarmuprun_callbacksr   r	   get_descrC   init_metricsr   r'   	enumerater    r   r   update_metricsplot_val_samplesplot_predictions	get_statscheck_statsdictzipr(   keysfinalize_metricsprint_resultsZlabel_loss_itemsr3   itemsformattuplevaluesZ	save_jsonopenr)   namejsondump	eval_jsonr   )r.   ZtrainerrU   r@   r   rY   rZ   r[   r,   dtbarr    r7   predsr$   resultsfr0   rF   r1   __call__i   s    
$


,"&"






*
0
:
*
$
&.
zBaseValidator.__call__Fc                 C   s  t |jd | jjd ft}|dddf |k}|| }|  }t| j 	 D ]2\}}|rddl
}	|||k }
|
 r|	jj|
dd\}}|
||f dk}| rd||| |f< q\t ||k}t |j}|jd r\|jd dkrr|||dddf |dddf f  ddd  }|t j|dddf ddd  }|t j|dddf ddd  }d||dddf t|f< q\tj|tj|jdS )	a7  
        Matches predictions to ground truth objects (pred_classes, true_classes) using IoU.

        Args:
            pred_classes (torch.Tensor): Predicted class indices of shape(N,).
            true_classes (torch.Tensor): Target class indices of shape(M,).
            iou (torch.Tensor): An NxM tensor containing the pairwise IoU values for predictions and ground of truth
            use_scipy (bool): Whether to use scipy for matching (more precise).

        Returns:
            (torch.Tensor): Correct tensor of shape(N,10) for 10 IoU thresholds.
        r   NT)Zmaximizer   r:   )Zreturn_index)Zdtyper   )npZzerosshaper&   Zastypeboolr3   numpyri   tolistscipyanyoptimizeZlinear_sum_assignmentZnonzeroarrayTZargsortuniqueintrV   Ztensorr   )r.   Zpred_classesZtrue_classesZiouZ	use_scipyZcorrectZcorrect_classi	thresholdr   Zcost_matrixZ
labels_idxZdetections_idxZvalidmatchesr0   r0   r1   match_predictions   s,    "
6"" zBaseValidator.match_predictions)eventc                 C   s   | j | | dS )zAppends the given callback.N)r
   appendr.   r   callbackr0   r0   r1   add_callback  s    zBaseValidator.add_callbackc                 C   s    | j |g D ]}||  qdS )z5Runs all callbacks associated with a specified event.N)r
   r^   r   r0   r0   r1   rf   	  s    zBaseValidator.run_callbacksc                 C   s   t ddS )z1Get data loader from dataset path and batch size.z:get_dataloader function not implemented for this validatorNNotImplementedError)r.   Zdataset_pathr\   r0   r0   r1   re     s    zBaseValidator.get_dataloaderc                 C   s   t ddS )zBuild dataset.z3build_dataset function not implemented in validatorNr   )r.   Zimg_pathr0   r0   r1   build_dataset  s    zBaseValidator.build_datasetc                 C   s   |S )zPreprocesses an input batch.r0   )r.   r7   r0   r0   r1   r     s    zBaseValidator.preprocessc                 C   s   |S )zPreprocesses the predictions.r0   )r.   r   r0   r0   r1   r     s    zBaseValidator.postprocessc                 C   s   dS )z2Initialize performance metrics for the YOLO model.Nr0   )r.   rU   r0   r0   r1   rh     s    zBaseValidator.init_metricsc                 C   s   dS )z/Updates metrics based on predictions and batch.Nr0   r.   r   r7   r0   r0   r1   rj   "  s    zBaseValidator.update_metricsc                 O   s   dS )z"Finalizes and returns all metrics.Nr0   )r.   r   kwargsr0   r0   r1   rr   &  s    zBaseValidator.finalize_metricsc                 C   s   i S )z1Returns statistics about the model's performance.r0   rF   r0   r0   r1   rm   *  s    zBaseValidator.get_statsc                 C   s   dS )zChecks statistics.Nr0   r.   r$   r0   r0   r1   rn   .  s    zBaseValidator.check_statsc                 C   s   dS )z.Prints the results of the model's predictions.Nr0   rF   r0   r0   r1   rs   2  s    zBaseValidator.print_resultsc                 C   s   dS )z"Get description of the YOLO model.Nr0   rF   r0   r0   r1   rg   6  s    zBaseValidator.get_descc                 C   s   g S )z9Returns the metric keys used in YOLO training/validation.r0   rF   r0   r0   r1   metric_keys:  s    zBaseValidator.metric_keysc                 C   s   |t   d| jt|< dS )z3Registers plots (e.g. to be consumed in callbacks).)r   	timestampN)timer-   r   )r.   ry   r   r0   r0   r1   on_plot?  s    zBaseValidator.on_plotc                 C   s   dS )z)Plots validation samples during training.Nr0   )r.   r7   nir0   r0   r1   rk   D  s    zBaseValidator.plot_val_samplesc                 C   s   dS )z-Plots YOLO model predictions on batch images.Nr0   )r.   r7   r   r   r0   r0   r1   rl   H  s    zBaseValidator.plot_predictionsc                 C   s   dS )z#Convert predictions to JSON format.Nr0   r   r0   r0   r1   pred_to_jsonL  s    zBaseValidator.pred_to_jsonc                 C   s   dS )z9Evaluate and return JSON format of prediction statistics.Nr0   r   r0   r0   r1   r|   P  s    zBaseValidator.eval_json)NNNNN)NN)F)N)__name__
__module____qualname____doc__r2   r   r   r   r`   r   rf   re   r   r   r   rh   rj   rr   rm   rn   rs   rg   propertyr   r   rk   rl   r   r|   r0   r0   r0   r1   r   '   s2   
%q
*

r   )r   rz   r   pathlibr   r   r   rV   Zultralytics.cfgr   r   Zultralytics.data.utilsr   r   Zultralytics.nn.autobackendr   Zultralytics.utilsr   r	   r
   r   r   Zultralytics.utils.checksr   Zultralytics.utils.opsr   Zultralytics.utils.torch_utilsr   r   r   r   r0   r0   r0   r1   <module>   s   