o
    ĎiB                     @  s   d dl mZ d dlZd dlZd dlZd dlmZ d dlmZ d dl	m
Z
 d dlZd dlZd dlmZ 	d,ddZddddddg dfd-d d!Zdddddg ddfd.d)d*Zed+kraee dS dS )/    )annotationsN)OrderedDict)Path)Literal)
AsciiTable   alld    c                   s  | j }|r
d}	|}
nd}	|dkrdnd}|dkrdnd}|d u r/|jd d	d
|jd d	n|d	} fddt|jD }fddt|jD }|dkr| jd }|d urft||jkd }|| }|d urx|d d d d |||f }nB|d d d d d d ||f }n2| jd }|d urt||jkd }|| }|d ur|d d |||f }n|d d d d ||f }t||dk dkrd}n	t	||dk }|rt
|	j|||
| ||d |S t
|	||| | |S )NzS {:<18} {} {:<{nameStrLen}} @[ IoU={:<9} | area={:>6s} | maxDets={:>3d} ] = {:0.3f}zB {:<18} {} @[ IoU={:<9} | area={:>6s} | maxDets={:>3d} ] = {:0.3f}r   zAverage PrecisionzAverage Recallz(AP)z(AR)r   z0.2f:c                      g | ]
\}}| kr|qS  r   ).0iaRng)areaRngr   X/home/jeff/fluffinator/venv/lib/python3.10/site-packages/sahi/scripts/coco_evaluation.py
<listcomp>       z'_cocoeval_summarize.<locals>.<listcomp>c                   r   r   r   )r   r   mDet)maxDetsr   r   r      r   	precisionrecall)
nameStrLen)paramsiouThrs	enumerate
areaRngLblr   evalnpwherelenmeanprintformat)cocoevalapiouThrcatIdxr   r   catNamer   piStrnameStrtitleStrtypeStriouStraindmindstmean_sr   )r   r   r   _cocoeval_summarize   sB   .
 
r6   bboxFi  )i   i $  l    d(	 dataset_pathstrresult_pathCOCOtypeCOCOevalmetric	classwiseboolmax_detectionsintout_dirstr | Path | Noneareas	list[int]c           A        s  t |tr|n|g}ddg}|D ]}||vrtd| dq|du r3tjddttdd	 d
d}|dur?t |ts?|g}|
durMt|
dkrMtdt	 }t
| }t|}W d   n1 sdw   Y  d|vrqi |d< ddl}|jdddd}t|| |j}W d   n1 sw   Y  zc||}t|j }|D ]M}d| d}d| }t| |}t
|}t|}W d   n1 sw   Y  z||}W n ty   td Y  nw ||||}|
durd|
d gd|
d g|
d |
d	 g|
d	 |
d gg|j_||j_|g|j_t |ts(t |tjs(|gn||j_dd	dddddddddd d!}|durS|D ]}||vrQtd"| dqB|  |  t|d	dd#|d$}t|d	dd#|d$}t|d	d%d#|d$}t|d	dd&|d$} t|d	dd'|d$}!t|d	dd(|d$}"t|d	dd&|d$}#t|d	dd'|d$}$t|d	dd(|d$}%t|ddd&|d$}&t|ddd'|d$}'t|ddd(|d$}(t||||#|$|%| |!|"|&|'|(gd|_ |r|j!d) })t||)j"d krtd*t| d+|)j"d  d}*t#|D ]\}+},|$|,d }-t|-d, }.|.|*kr|.n|*}*qg }/t#|D ] \}+},|j%|,gd-}0t|0dkr8q#|$|,d }-t|d	|+d#||-d, |*d.}1t|d	|+d&||-d, |*d.}2t|d	|+d'||-d, |*d.}3t|d	|+d(||-d, |*d.}4t|d	d|+d#||-d, |*d/}5t|d	d|+d&||-d, |*d/}6t|d	d|+d'||-d, |*d/}7t|d	d|+d(||-d, |*d/}8|/| d0|-d,  d1t&|1d2f |/| d0|-d,  d3t&|2d2f |/| d0|-d,  d4t&|3d2f |/| d0|-d,  d5t&|4d2f |/| d0|-d,  d6t&|5d2f |/| d0|-d,  d7t&|6d2f |/| d0|-d,  d8t&|7d2f |/| d0|-d,  d9t&|8d2f q#t'dt|/d  tt(j)|/ d:d;g d  }9t(j* fd<d=t+ D  }:|9g};|;d>d= |:D 7 };t,|;}<td|<j-  |du rg d?}|D ]}| d0| }=t&|j ||  d@}>|>||=< q|j }1|1d d@dA|1d	 d@dA|1d d@dA|1d d@dA|1d d@dA|1d d@dA|1d d@dA|1d d@dA|1d d@|| dB< |rdCdD |/D |dE< qW t./| nt./| w |	s	t0|j1}	t0|	j2d
d
dF t3t0|	dG }?t
|?ddHdI}@tj||@ddJdK W d   n	1 s6w   Y  tdL|?  ||?dMS )Na(  Evaluation in COCO protocol.

    Args:
        dataset_path (str): COCO dataset json path.
        result_path (str): COCO result json path.
        COCO, COCOeval: Pass COCO and COCOeval class after safely imported
        metric (str | list[str]): Metrics to be evaluated. Options are
            'bbox', 'segm', 'proposal'.
        classwise (bool): Whether to evaluating the AP for each class.
        max_detections (int): Maximum number of detections to consider for AP
            calculation.
            Default: 500
        iou_thrs (List[float], optional): IoU threshold used for
            evaluating recalls/mAPs. If set to a list, the average of all
            IoUs will also be computed. If not specified, [0.50, 0.55,
            0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95] will be used.
            Default: None.
        metric_items (list[str] | str, optional): Metric items that will
            be returned. If not specified, ``['AR@10', 'AR@100',
            'AR@500', 'AR_s@500', 'AR_m@500', 'AR_l@500' ]`` will be
            used when ``metric=='proposal'``, ``['mAP', 'mAP50', 'mAP75',
            'mAP_s', 'mAP_m', 'mAP_l', 'mAP50_s', 'mAP50_m', 'mAP50_l']``
            will be used when ``metric=='bbox' or metric=='segm'``.
        out_dir (str): Directory to save evaluation result json.
        areas (List[int]): area regions for coco evaluation calculations
    Returns:
        dict:
            eval_results (dict[str, float]): COCO style evaluation metric.
            export_path (str): Path for the exported eval result json.
    r7   segmzmetric z is not supportedNg      ?gffffff?g!@r   T)endpoint   zD3 integers should be specified as areas, representing 3 area regionsinfor   wz.jsonF)modesuffixdeletezEvaluating z...
z2The testing results of the whole dataset is empty.                  	   
      )mAPmAP75mAP50mAP_smAP_mmAP_lmAP50_smAP50_mmAP50_lAR_sAR_mAR_lzmetric item r   )r'   r(   r   r   g      ?smallmediumlarger   zThe number of categories z* is not equal to the number of precisions name)catIds)r'   r)   r   r   r*   r   )r'   r(   r)   r   r   r*   r   __mAPz0.3f_mAP_s_mAP_m_mAP_l_mAP50_mAP50_s_mAP50_m_mAP50_lcategoryAPc                   s   g | ]	}|d   qS )Nr   )r   r   num_columnsresults_flattenr   r   r   <  s    z!evaluate_core.<locals>.<listcomp>c                 S  s   g | ]}|qS r   r   )r   resultr   r   r   r   >  s    )	rY   r[   rZ   r\   r]   r^   r_   r`   ra   z.3f _mAP_copypastec                 S  s   i | ]\}}||qS r   r   )r   keyvaluer   r   r   
<dictcomp>P  s    z!evaluate_core.<locals>.<dictcomp>results_per_category)parentsexist_okz	eval.jsonzutf-8)encoding),r   )indent
separatorsz5COCO evaluation results are successfully exported to )eval_resultsexport_path)4
isinstancelistKeyErrorr    linspacerB   roundr"   
ValueErrorr   openjsonloadtempfileNamedTemporaryFiledumprh   catskeysr$   loadRes
IndexErrorr   r   ri   r   ndarrayr   evaluate
accumulater6   appendstatsr   shaper   loadCats	getImgIdsfloatmin	itertoolschainzip_longestranger   tableosunlinkr   parentmkdirr9   )Ar8   r:   r;   r=   r>   r?   rA   iou_thrsmetric_itemsrC   rE   metricsallowed_metricsr   fdataset_dictr   tmp_filetemp_dataset_pathcocoGtcat_idsmsgiou_type	json_fileresultscocoDtcocoEvalcoco_metric_namesmetric_itemrY   r[   rZ   r_   r`   ra   r\   r]   r^   rb   rc   rd   
precisionsmax_cat_name_lenidxcatIdnmcat_name_lenr~   	image_idsr'   ap_sap_map_lap50ap50_sap50_map50_lheaders
results_2d
table_datar   r{   valr   outfiler   ru   r   evaluate_core>   s  , 







"


				


&
&&&&&&*
0

r   dataset_json_pathresult_json_path
str | NoneLiteral['bbox', 'segm']r   list[float] | float | Nonereturn_dictc	                 C  s\   zddl m}	 ddlm}
 W n ty   tdw t| ||||||||	|
d
}|r,|S dS )a  
    Args:
        dataset_json_path (str): file path for the coco dataset json file
        result_json_path (str): file path for the coco result json file
        out_dir (str): dir to save eval result
        type (bool): 'bbox' or 'segm'
        classwise (bool): whether to evaluate the AP for each class
        max_detections (int): Maximum number of detections to consider for AP alculation. Default: 500
        iou_thrs (float): IoU threshold used for evaluating recalls/mAPs
        areas (List[int]): area regions for coco evaluation calculations
        return_dict (bool): If True, returns a dict with 'eval_results' 'export_path' fields.
    r   )r;   )r=   zYPlease run "pip install -U pycocotools" to install pycocotools first for coco evaluation.)
r8   r:   r>   r?   rA   r   rC   rE   r;   r=   N)pycocotools.cocor;   pycocotools.cocoevalr=   ModuleNotFoundErrorr   )r   r   rC   r<   r?   rA   r   rE   r   r;   r=   rx   r   r   r   r   a  s.   r   __main__)r   NNr   r	   r
   N)r8   r9   r:   r9   r;   r<   r=   r<   r>   r9   r?   r@   rA   rB   rC   rD   rE   rF   )r   r9   r   r9   rC   r   r<   r   r?   r@   rA   rB   r   r   rE   rF   r   r@   )
__future__r   r   r   r   collectionsr   pathlibr   typingr   firenumpyr    terminaltablesr   r6   r   r   __name__Firer   r   r   r   <module>   sB    
4  (0