o
    ĎiC                     @  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	Z	d dl
Zd dlmZ zd dlmZ d dlmZ dZW n eyG   d	ZY nw z
d dlmZ dZW n ey]   d	ZY nw eeg d
eg deg deg deg deg deg dgZd;ddZd<ddZdd Zdd Zd<d d!Zd"d# Z d=d>d'd(Z!				$d?d)d*Z"dd+d	g d,d$d	fd@d8d9Z#e$d:kre	%e# dS dS )A    )annotationsN)Pool)Path)logger)COCO)COCOevalTF)皙?r   r   )333333?r	   r	   )ףp=
?gRQ?gGz?)      ?r
   g333333?)g
ףp=
?g?gRQ?)      ?g(\?g{Gz?)   r	   r   outDir
str | Path
class_namestriou_typereturn	list[str]c                 C  s  g }g d}g d}t t|D ]}|d|df }	|d | d ||  }
g }g }|	D ]I}|jdkrTt|jd f}t|D ]\}}||dk  ||< q?|| n|| t||dk rj||dk  }nt	d}|| q+|
dt|d j t }td}t t|D ]0}|j| ||d  g d	d
d |j| || ||d  t| td|| dd||  d qtd td tdd tdd t|
 t  tt||
 d }|| t| || q|S )NallareasmallmediumlargeC75C50LocSimOthBGFN.r   -r   o   )r   r   r   r   )color	linewidth[z.3f])r%   labelrecall	precision      ?.png)rangelenndimnpzerosshape	enumeratemeanappendarrayinsertpltfiguresubplotplotfill_betweenCOLOR_PALETTEr   xlabelylabelxlimylimtitlelegendr   savefigclose)rspsr   r   r   export_path_list	areaNamestypesiarea_psfigure_titleapsps_curveps_ps_meanindps_thresholdapfigaxkexport_path rZ   \/home/jeff/fluffinator/venv/lib/python3.10/site-packages/sahi/scripts/coco_error_analysis.py	_makeplot+   sT   









r\   c              
   C  sl   |D ]1}|  }|r|dkr|dkr|d d}n|d}| j|| | d  |fdddd	d
d qdS )zEAttach a text label above each bar in *rects*, displaying its height.r   r   d   z2.0f   )r      zoffset pointscenterbottomzx-small)xyxytext
textcoordshavafontsizeN)
get_heightannotateget_x	get_width)rW   rects
is_percentrectheight
text_labelrZ   rZ   r[   
_autolabel_   s   rq   c              
   C  sh  g d}g d}t  \}}tt|}	d}
g }|d | d d }tt|d D ]O}||ddf }g }|jD ]}t||d	k rL||d	k  }ntd}|	| q9|	|j
|	|
d
  |d |
 t|  ||
t| || t| d q+|d || ||	 || |  |D ]}t|| qtt|| d }|| t | |S )Nr   r   r	   r"   zap bar plotr   .r   r#   r^   )r)   r%   zMean Average Precision (mAP)r-   )r9   subplotsr1   aranger/   r.   Tr5   r7   r6   barr>   
set_ylabel	set_title
set_xticksset_xticklabelsrD   rq   r   r   rE   rF   )_rH   r   r   r   rJ   rK   rV   rW   xwidth
rects_listrN   rX   type_psrO   rQ   rU   rl   rY   rZ   rZ   r[   _makebarplotr   sF   








r   c           	      C  s~   | j j}dd |D }| j j}tt||}t|d}| jD ]}|r<|d D ]}|s;|t|d  }||  d7  < q'q|S )Nc                 S  s   g | ]}t |qS rZ   )r   ).0aRngrZ   rZ   r[   
<listcomp>       z._get_gt_area_group_numbers.<locals>.<listcomp>r   gtIgnorer   r   )paramsareaRng
areaRngLbldictzipfromkeysevalImgsr   )	cocoEvalr   
areaRngStrr   areaRngStr2areaRngLblareaRngLbl2NumberevalImgr   aRngLblrZ   rZ   r[   _get_gt_area_group_numbers   s   
r   c                 C  s   t | }| }|rtd| t \}}tt|}d}d}	||t	|
 |}
|d ||	 || || t||
dd tt||	 d }|  || t| |S )Nz%number of annotations per area group:r	   z$number of annotations per area groupNumber of annotationsF)rm   r-   )r   keysprintr9   rr   r1   rs   r/   ru   listvaluesrv   rw   rx   ry   rq   r   r   tight_layoutrE   rF   )r   r   verboser   r   rV   rW   r{   r|   rN   rl   rY   rZ   rZ   r[    _make_gt_area_group_numbers_plot   s&   






r   c                 C  s   d}dd | j j D }d}t \}}|jt||d |d |	d |
| tt|| d }|  || t| |S )	Nr]   c                 S  s   g | ]}|d  qS )arearZ   )r   annrZ   rZ   r[   r      r   z0_make_gt_area_histogram_plot.<locals>.<listcomp>z"gt annotation areas histogram plot)binszSquareroot Arear   r-   )cocoGtannsr   r9   rr   histr1   sqrt
set_xlabelrv   rw   r   r   r   rE   rF   )r   r   n_binsareasrN   rV   rW   rY   rZ   rZ   r[   _make_gt_area_histogram_plot   s   




r     max_detectionsintc                 C  s  | |d }td| d  d|d  d i }t|}	| |d }| }
|	jd }g }|D ]}|d |kr>|| q1||	jd< |	  t|}|j|d	 gd
}t	|jd D ]+\}}|d |v r|d |krd|jd | d< d|jd | d< ||jd | d< q]t
|t|	|}|
|j_|g|j_dg|j_d|j_|rd|d gd|d g|d |d g|d |d gg|j_|  |  |jd dd d |d d d d f }||d< t|}t	|jd D ]&\}}|d |krd|jd | d< d|jd | d< ||jd | d< qt
|t|	|}|
|j_|g|j_dg|j_d|j_|rMd|d gd|d g|d |d g|d |d gg|j_|  |  |jd dd d |d d d d f }||d< | |fS )Nr   z--------------analyzing r   r"   name---------------r   category_idsupercategory)supNmsignoreiscrowd皙?r^   r+   ps_supercategoryps_allcategory)loadCatsr   copydeepcopy	getImgIdsdatasetr6   createIndex	getCatIdsr4   r   r   imgIdsmaxDetsiouThrsuseCatsr   evaluate
accumulateeval)rX   cocoDtr   catIdr   r   r   nmrQ   dtr   dt_annsselect_dt_annsr   gtchild_catIdsidxr   r   r   rZ   rZ   r[   _analyze_individual_category   sx   








$




$r   c           (        s  |D ]}|dvrt d| dq d urt dkrt d|d u r.t| j}t|d }tj|d }tj|sIt	d| d	 t
| i }	t|}
t|
}W d    n1 s_w   Y  d
|vrli |d
< dd l}|jdddd}t|| |j}W d    n1 sw   Y  zHt||  }|D ]0}|d | d }tj|}tj|st	d| d	 t
| |ttt}||j_g d|j_g|j_ d urd d gd d g d  d g d  d gg|j_|  |  g } }t |D ]\}}j|gd}t|dkr-|!| qt"|j#d j$}t||d< t%&|}t |D ](\}}|j#d d d d d |d d d d f |d d d d |d d d d f< qFt%'|t%&dg|j$dd  R g}|jj(}t)dd} fddt |D }|*t+|}W d    n	1 sw   Y  i }t |D ]\}},|d }t	d|d  d|d  d || } || d krt d| d| d  | d d  }!| d d! }"|!|dd d |d d d d f< |"|dd d |d d d d f< d"|d#d d |d d d d f |dd d |d d d d f d"k< d|d#d d |d d d d f |dd d |d d d d f dk< d$|d%d d |d d d d f< |d -dd&-tj.d&}#t/||d d d d |f ||#}$|rt0||d d d d |f ||#}%nd }%|$|%d'||d < qt/|||d(}$|rt0|||d(}%t1||d)d*}&t2||d+}'nd,\}%}&}'||%|$|&|'d-d.|	|< qW t3| nt3| w t	d/|  |	S )0N)bboxsegmz	res_type z is not supportedr_   zD3 integers should be specified as areas, representing 3 area regionscoco_error_analysis/z-------------create z-----------------infor   wz.jsonF)modesuffixdelete)r   r   r   r^   r   )catIdsr+      0   )	processesc              	     s"   g | ]\}}|| fqS rZ   rZ   )r   rX   r   r   r   r   r   r   rZ   r[   r   {  s    z$_analyse_results.<locals>.<listcomp>z--------------saving r"   r   r   zk z != analyze_result[0] r   r   r#      r,      rz   )curvesbar_plotallclassT)r   r   r   )r   r   )NNN)r   r   gt_area_group_numbersgt_area_histogram)	classwiseoverallz9COCO error analysis results are successfully exported to )4
ValueErrorr/   r   parentr   ospathdirnameexistsr   makedirsopenjsonloadtempfileNamedTemporaryFiledumpr   r   loadResr   r   r   r   r   r   r   r   r   r   r   r   r4   r6   r   r   r3   r1   r2   vstackrecThrsr   starmapr   r   replacesepr\   r   r   r   unlink)(res_fileann_file	res_typesout_dir
extraplotsr   r   res_type	directoryresult_type_to_export_pathsfann_dictr   tmp_filetemp_ann_filer   res_out_dirres_directoryr   present_cat_idsr   rX   r   	image_idsmatrix_shaperH   r   poolargsanalyze_resultsclassname_to_export_path_listr   analyze_resultr   r   normalized_class_namecurve_export_path_listbar_plot_pathgt_area_group_numbers_plot_pathgt_area_histogram_plot_pathrZ   r   r[   _analyse_results*  s   	











J&@@"$
_r  r   )i   i $  l    d(	 dataset_json_pathresult_json_pathr   
str | Nonetypeno_extraplotsboolr   	list[int]return_dictdict | Nonec           	   	   C  sR   t std tdtstd tdt|| |g|| ||d}|r'|S dS )a8  
    Args:
        dataset_json_path (str): file path for the coco dataset json file
        result_json_paths (str): file path for the coco result json file
        out_dir (str): dir to save analyse result images
        no_extraplots (bool): dont export export extra bar/stat plots
        type (str): 'bbox' or 'mask'
        areas (List[int]): area regions for coco evaluation calculations
        max_detections (int): Maximum number of detections to consider for AP alculation. Default: 500
        return_dict (bool): If True, returns a dict export paths.
    zBPlease run 'uv pip install -U matplotlib' first for visualization.zmatplotlib not installedzCPlease run 'uv pip install -U pycocotools' first for Coco analysis.zpycocotools not installed)r   r   r   r   r   N)has_matplotlibr   errorModuleNotFoundErrorhas_pycocotoolsr  )	r  r  r   r  r  r   r   r  resultrZ   rZ   r[   analyse  s$   

	r   __main__)r   r   r   r   r   r   r   r   )T)Nr   )r   r   )NNNr   )r  r   r  r   r   r  r  r   r  r  r   r  r   r   r  r  r   r  )&
__future__r   r   r   r   multiprocessingr   pathlibr   firenumpyr1   sahi.loggerr   pycocotools.cocor   pycocotools.cocoevalr   r  ImportErrormatplotlib.pyplotpyplotr9   r  r   r7   r>   r\   rq   r   r   r   r   r   r  r   __name__FirerZ   rZ   rZ   r[   <module>   sn    

40
 D
 )