a
    ^Df                     @   s   d dl Z d dlZd dlm  mZ d dlmZ d dlm	Z	 d dl
mZmZmZmZ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 dd	lmZ dd
lmZmZ ddlmZm Z  ddl!m"Z"m#Z# ddl$m%Z%m&Z& ddl'm(Z( edZ)G dd dZ*dS )    N)defaultdict)Path)	AnyCallableDictIterableIteratorMappingOptionalTypeVarUnion)warn)tqdm   )
Annotation)open_atomic)BoundingBox	BoxFormat)ParsingErrorUnknownImageFormat)PathLikeglob)IMAGE_EXTENSIONSget_image_size
thread_mapTc                   @   sP  e Zd ZdZdddeee  dddZeedd	d
Z	eee dddZ
edddZdd Zdd ZeedddZddedddZddd d dddZd d dddZd d ddd Zeeef d d!d"d#Zed$d% Zeee dd&d'Zedd(d)Zd*dd+d,Zedd-ee gef ee  ed d.d/d0Z!eddd1e"eee#gef ed d2d3d4Z$ede%j&dd5d6dddd7e"ee" eeee eed d8d9d:Z'ed6ddd;e"e"eed d<d=d>Z(ed6ddd;e"e"eed d<d?d@Z)ed6ddAe"e"ed dBdCdDZ*ed6ddAe"e"ed dBdEdFZ+ed6ddAe"e"ed dBdGdHZ,edd-e"ed dIdJdKZ-edd-e"ed dIdLdMZ.edd-e"ed dIdNdOZ/edd-e"e"ed dPdQdRZ0edd-e"ed dIdSdTZ1edd-e"ed dUdVdWZ2dd-e"ed dUdXdYZ3edd-e"dZdZed d[d\d]Z4edd-e"ed dUd^d_Z5ed`daddbe"eeee" d dcdddeZ6dd-eegdf edfdgdhZ7de%j&ddid5dddje"eeee8eef f  e%eeeeedkdldmZ9ddddne"eeee8eef f  eedodpdqZ:ddddne"eeee8eef f  eedodrdsZ;dddte"eeee8eef f  edudvdwZ<dddte"eeee8eef f  edudxdyZ=dddte"eeee8eef f  edudzd{Z>dd-e"ed|d}d~Z?dd-e"ed|ddZ@dd-e"ed|ddZAdd-e"ed|ddZBddddded ed eeeCdddZDddddde"ed ed eedddZEdd-e"edddZFdd-eeGjHdddZIdd-e"edddZJd`dadde#eeeeCdddZKd`dadde"e#eeedddZLee"ddddZMee"ddddZNdd-ed-ddZOedddZPdS )AnnotationSetze
    A set of annotations of multiple and distinct images, most commonly refered to a 'dataset'.
    NFoverride)annotationsc                C   s6   i | _ |dur&|D ]}| j||d qd| _d| _dS )a  
        Create an `AnnotationSet` from multiple image annotations. Each annotation should be unique,
        i.e. multiple annotations for a single image (as idendified by its `image_id`) is not
        allowed.

        Parameters:

        * `annotation`: an iterable of image annotations.
        * `override`: if `True`, image annotations not unique are allowed and only the last one in
        the iterator will be kept, else an error is thrown.
        Nr   )_annotationsadd_id_to_label_id_to_imageid)selfr    r   
annotation r'   a/nfs/NAS7/SABIOD/METHODE/ermites/ermites_venv/lib/python3.9/site-packages/globox/annotationset.py__init__%   s    zAnnotationSet.__init__)image_idreturnc                 C   s
   | j | S )z
        Get the image annotation with the corresponding `image_id`. Will raise an exception
        if the image ID is not present in the dataset.
        r!   r%   r*   r'   r'   r(   __getitem__D   s    zAnnotationSet.__getitem__c                 C   s   | j |S )z
        Get the image annotation with the corresponding `image_id`, if present in the dataset
        (else `None` is returned).
        )r!   getr-   r'   r'   r(   r/   K   s    zAnnotationSet.get)r+   c                 C   s
   t | jS )z)The number of annotations in the dataset.)lenr!   r%   r'   r'   r(   __len__R   s    zAnnotationSet.__len__c                 c   s   | j  E d H  d S N)r!   valuesr1   r'   r'   r(   __iter__V   s    zAnnotationSet.__iter__c                 C   s
   | j  S )z7A view on the image annotation items (key-value pairs).)r!   itemsr1   r'   r'   r(   r6   Y   s    zAnnotationSet.itemsr&   r+   c                 C   s   |j | j v S )zLReturn `True` if a given annotation is present in the dataset, else `False`.)r*   r!   keysr%   r&   r'   r'   r(   __contains__]   s    zAnnotationSet.__contains__r&   c                C   s2   |s"|j | jvs"J d|j  d|| j|j < dS )a^  
        Add an annotation to the dataset.

        Parameters:

        * `annotation`: the annotation to add.
        * `override`: set to `True` if the annotation may already be in the dataset and the former
        it should be replaced by the new one. If `False` and the annotation is already in the
        dataset, an error is thrown.
        zThe annotation with id 'zR' is already present in the set (set `override` to True to remove this assertion).N)r*   	image_idsr!   )r%   r&   r   r'   r'   r(   r"   a   s
    zAnnotationSet.add)otherr+   c                C   s,   |s| j |j sJ d| j|j | S )a9  
        Add annotations from another datasetset to this one.

        Parameters:

        * `other`: the annotations to add.
        * `override`: if `True`, image annotations in `other` that aren't unique are allowed and
        only the last one in the iterator will be kept, else an error is thrown.
        zXsome image ids are already in the set (set 'override' to True to remove this assertion).)r<   
isdisjointr!   update)r%   r=   r   r'   r'   r(   r?   t   s    zAnnotationSet.updatec                 C   s
   |  |S r3   )r?   r%   r=   r'   r'   r(   __ior__   s    zAnnotationSet.__ior__c                 C   s   t  | |S r3   )r   r?   r@   r'   r'   r(   __or__   s    zAnnotationSet.__or__)mappingr+   c                 C   s   | D ]}| | q| S )z
        Update all the bounding box labels according to the provided dictionary which maps former
        names to new names. If a label name is not present in the dictionary keys, then it won't
        be updated.
        )
map_labels)r%   rC   r&   r'   r'   r(   rD      s    zAnnotationSet.map_labelsc                 C   s
   | j  S )z/A view on the set of image IDs of this dataset.)r!   r8   r1   r'   r'   r(   r<      s    zAnnotationSet.image_idsc                 c   s   | D ]}|j E dH  qdS )z5An iterator of all the bounding boxes of the dataset.N)boxesr9   r'   r'   r(   	all_boxes   s    zAnnotationSet.all_boxesc                 C   s   t dd | D S )z,The number of bounding boxes in the dataset.c                 s   s   | ]}t |jV  qd S r3   )r0   rE   ).0annr'   r'   r(   	<genexpr>       z)AnnotationSet.nb_boxes.<locals>.<genexpr>)sumr1   r'   r'   r(   nb_boxes   s    zAnnotationSet.nb_boxeszset[str]c                 C   s   dd | j D S )z<The set of the different label names present in the dataset.c                 S   s   h | ]
}|j qS r'   )label)rG   br'   r'   r(   	<setcomp>   rJ   z(AnnotationSet._labels.<locals>.<setcomp>)rF   r1   r'   r'   r(   _labels   s    zAnnotationSet._labelsverbose)parseriterablerR   r+   c                C   s   t | |d|d}t|S )NParsingdescrR   )r   r   )rS   rT   rR   r    r'   r'   r(   	from_iter   s    zAnnotationSet.from_iter)	recursiverR   )folder	extensionrS   rR   r+   c                C   sJ   t |   } |  s(J d|  dtt| ||d}tj|||dS )Nz
Filepath 'z$' is not a folder or does not exist.)rY   rQ   )r   
expanduserresolveis_dirlistr   r   rX   )rZ   r[   rS   rY   rR   filesr'   r'   r(   from_folder   s    	
zAnnotationSet.from_folder.txtz.jpg)image_folder
box_formatrelativefile_extensionimage_extension	separator	conf_lastrR   )rZ   rc   rf   rg   rh   ri   rR   r+   c          
         s   t |   } |  sJ ds*J r>dus>J ddurbt    sbJ t td fdd}	tj| ||	|dS )zThis method won't try to retreive the image sizes by default. Specify `image_folder` if you need them.
        `image_folder` is required when `relative` is True..NzTWhen `relative` is set to True, `image_folder` must be provided to read image sizes.)filer+   c              	      s   d urd }t D ](}| |j}| }| r|} q:q|d usTJ d| j d|j}zt|}W q ty   td| dY q0 nd }| j }}tj| | |dS )NzImage z/ does not exist, unable to read the image size.z"Unable to read image size of file z=. The file may be corrupted or the file format not supported.)	file_pathr*   rd   re   
image_sizerh   ri   )	r   with_suffixnameis_filer   r   r   r   from_txt)rk   
image_pathZ	image_extr*   pathrm   rd   ri   rg   rc   re   rh   r'   r(   _get_annotation   s<    
z/AnnotationSet.from_txt.<locals>._get_annotationr[   rS   rR   )r   r\   r]   r^   
startswithr   r   ra   )
rZ   rc   rd   re   rf   rg   rh   ri   rR   ru   r'   rt   r(   rq      s$    'zAnnotationSet.from_txt)rg   ri   rR   )rZ   rc   ri   rR   r+   c             
   C   s   t j| |tjd|d ||dS )NT)rc   rd   re   rg   rh   ri   rR   )r   rq   r   ZXYWHrZ   rc   rg   ri   rR   r'   r'   r(   
_from_yolo  s    	zAnnotationSet._from_yoloc                C   s"   t dtdd tj| ||||dS )NzK'from_yolo' is deprecated. Please use `from_yolo_darknet` or `from_yolo_v5`   category
stacklevelrc   rg   ri   rR   )r   DeprecationWarningr   ry   rx   r'   r'   r(   	from_yolo'  s    	zAnnotationSet.from_yolo)rg   rR   )rZ   rc   rR   r+   c                C   s   t j| ||d|dS )NFr~   r   ry   rZ   rc   rg   rR   r'   r'   r(   from_yolo_darknet>  s    zAnnotationSet.from_yolo_darknetc                C   s   t j| ||d|dS )NTr~   r   r   r'   r'   r(   from_yolo_v5N  s    zAnnotationSet.from_yolo_v5c                C   s   t j| |||dS )N)rc   rg   rR   )r   r   r   r'   r'   r(   from_yolo_v7^  s    zAnnotationSet.from_yolo_v7)rZ   rR   r+   c                C   s   t j| dtj|dS )N.xmlrv   )r   ra   r   from_xmlrZ   rR   r'   r'   r(   r   m  s    
zAnnotationSet.from_xmlc                C   s   t j| |dS NrQ   r   r   r   r'   r'   r(   from_pascal_vocs  s    zAnnotationSet.from_pascal_vocc                C   s   t j| |dS r   r   r   r'   r'   r(   from_imagenetw  s    zAnnotationSet.from_imagenet)rl   rc   rR   r+   c                   sR  t |   } |  r"| jdks2J d|  dt |  }| sZJ d| dt }| jdd}t	|}t
|d| d	D ]  d
 } d } fdddD } d}	|	d ur|	dkrt|	}	nd }	||jvr|| }
t|
}|t||d || }|tj|t||	d|jd qW d    n1 sD0    Y  |S )N.csvzOpenImage annotation file z must be a csv file.zImage folder z must be a valid directory. newlinerU   rW   disableImageID	LabelNamec                 3   s   | ]}t  | V  qd S r3   float)rG   rrowr'   r(   rI     rJ   z/AnnotationSet.from_openimage.<locals>.<genexpr>)XMinYMinXMaxYMax
Confidence)r*   rm   T)rM   coords
confidencere   rm   )r   r\   r]   rp   suffixr^   r   opencsv
DictReaderr   r/   r   r<   r   r"   r   r   createtuplerm   )rl   rc   rR   r    freaderr*   rM   r   r   rr   rm   r&   r'   r   r(   from_openimage{  sP    





&
zAnnotationSet.from_openimagec                C   s   t j| dtj|dS )N.jsonrv   )r   ra   r   from_labelmer   r'   r'   r(   r     s    
zAnnotationSet.from_labelme)rl   rR   r+   c             	   C   s6  t |   } |  r"| jdks2J d|  d|  }t|}W d    n1 sZ0    Y  dd |d D }dd |d D }|d	 }t|d
| dD ]j}||d  }|t	|d  }	t
dd |d D }
|d}|d urt|}|tj|	|
|tjd qt| }||_dd | D |_|S )Nr   COCO annotation file  must be a json file.c                 S   s   i | ]}|d  t |d qS )idro   strrG   dr'   r'   r(   
<dictcomp>  rJ   z+AnnotationSet.from_coco.<locals>.<dictcomp>
categoriesc                 S   s   i | ]}|d  t |qS )r   )r   Z_from_coco_partialr   r'   r'   r(   r     s   imagesr    rU   r   r*   category_idc                 s   s   | ]}t |V  qd S r3   r   rG   cr'   r'   r(   rI     rJ   z*AnnotationSet.from_coco.<locals>.<genexpr>bboxscorerM   r   r   rd   c                 S   s   i | ]\}}||j qS r'   )r*   )rG   idxrH   r'   r'   r(   r     s   )r   r\   r]   rp   r   r   jsonloadr   intr   r/   r   r"   r   r   r   LTWHr   r4   r#   r6   r$   )rl   rR   r   contentid_to_labelid_to_annotationelementselementr&   rM   r   r   annotation_setr'   r'   r(   	from_coco  sF    

(
	zAnnotationSet.from_cococ             	   C   sF  t |  }| r"|jdks2J d| d| j}| j}|d urN|d usVJ di }| }t	|}W d    n1 s0    Y  t
|d| dD ]}||d  }	| |	 }
|	|vrt|	|
jd}|||	< n||	 }|t|d	  }td
d |d D }t|d }|tj|||tjd qt| }||_||_|S )Nr   r   r   zThe AnnotationSet instance should have been created with `AnnotationSet.from_coco()` or should have `self.id_to_label` and `self.id_to_image_id` populated. If not the case use the static method `AnnotationSet.from_coco_results()` instead.rU   r   r*   )rm   r   c                 s   s   | ]}t |V  qd S r3   r   r   r'   r'   r(   rI   
  rJ   z-AnnotationSet.from_results.<locals>.<genexpr>r   r   r   )r   r\   r]   rp   r   r#   r$   r   r   r   r   r   rm   r   r   r   r"   r   r   r   r   r   r4   )r%   rl   rR   r   id_to_imageidr   r   r    r   r*   Zgt_annr&   rM   r   r   r   r'   r'   r(   from_results  sJ    

(
	zAnnotationSet.from_resultszdict[int, str])rl   r   r   rR   r+   c             	   C   s  t |   } |  r"| jdks2J d|  di }|  }t|}W d    n1 s^0    Y  t|d| dD ]~}||d  }||vrt	|}	|	||< n|| }	|t
|d  }
tdd	 |d
 D }t|d }|	tj|
||tjd qxt| }||_||_|S )Nr   r   r   rU   r   r*   r   c                 s   s   | ]}t |V  qd S r3   r   r   r'   r'   r(   rI   ;  rJ   z2AnnotationSet.from_coco_results.<locals>.<genexpr>r   r   r   )r   r\   r]   rp   r   r   r   r   r   r   r   r   r   r"   r   r   r   r   r   r4   r#   r$   )rl   r   r   rR   r   r   r    r   r*   r&   rM   r   r   r   r'   r'   r(   from_coco_results  s>    


(
	zAnnotationSet.from_coco_resultsc                C   s   t |   } |  r"| jdks2J d|  d|  }t| }W d    n1 s^0    Y  t	|
d}tjtj||dS )Nr   zCVAT annotation file z must be a xml file.imagerQ   )r   r\   r]   rp   r   r   etparsegetrootr_   iterr   rX   r   	from_cvat)rl   rR   r   rootZimage_nodesr'   r'   r(   r   M  s    

,zAnnotationSet.from_cvatZlabel_idr   )	label_keyconfidence_keyrc   )rl   r   r   rc   r+   c                C   s   t |   } |d ur8t |  }| s8td|  rJ| jdksZtd|  d|  }t	|}W d    n1 s0    Y  |
d|}t }| D ]>}tj|||d}	|d ur||	j }
t|
}||	_||	 q|S )Nz(Invalid `image_folder`: not a directory.r   zVIA JSON annotation file z must be a valid json file.Z_via_img_metadata)r   r   )r   r\   r]   r^   r   rp   r   r   r   r   r/   r   r4   r   from_via_jsonr*   r   rm   r"   )rl   r   r   rc   r   r   Zimg_annsr    Zimg_annr&   Zimg_pathrm   r'   r'   r(   r   ^  s.    

(
zAnnotationSet.from_via_json)save_fnrR   c                C   s   t || d|d d S )NSavingrV   r   )r%   r   rR   r'   r'   r(   save_from_it  s    zAnnotationSet.save_from_it )label_to_idrd   re   rh   rf   ri   rR   )save_dirr   rd   re   rh   rf   ri   rR   c          
         sL   t   jdd td fdd}	| j|	|d d S )NTexist_okr;   c                    s.   | j }| }| j| d d S )N)r   rd   re   rh   ri   )r*   rn   save_txt)r&   r*   rs   rd   ri   rf   r   re   r   rh   r'   r(   _save  s    z%AnnotationSet.save_txt.<locals>._saverQ   r   r\   r]   mkdirr   r   )
r%   r   r   rd   re   rh   rf   ri   rR   r   r'   r   r(   r     s    zAnnotationSet.save_txtr   ri   rR   )r   r   ri   rR   c                   sD   t   jdd td fdd}| j||d d S )NTr   r;   c                    s(   t | jd }| j| d d S )Nrb   )r   ri   )r   r*   rn   
_save_yolor&   rs   ri   r   r   r'   r(   r     s    z'AnnotationSet._save_yolo.<locals>._saverQ   r   )r%   r   r   ri   rR   r   r'   r   r(   r     s    zAnnotationSet._save_yoloc                C   s$   t dtdd | j||||d d S )NzK'save_yolo' is deprecated. Please use `save_yolo_darknet` or `save_yolo_v5`rz   r{   r   )r   r   r   )r%   r   r   ri   rR   r'   r'   r(   	save_yolo  s    zAnnotationSet.save_yolor   rR   )r   r   rR   c                C   s   | j ||d|d d S )NFr   r   r%   r   r   rR   r'   r'   r(   save_yolo_darknet  s    zAnnotationSet.save_yolo_darknetc                C   s   | j ||d|d d S )NTr   r   r   r'   r'   r(   save_yolo_v5  s    zAnnotationSet.save_yolo_v5c                C   s   | j |||d d S )Nr   )r   r   r'   r'   r(   save_yolo_v7  s    zAnnotationSet.save_yolo_v7)r   rR   c                   s@   t      jdd td fdd}| j||d d S )NTr   r;   c                    s"    t | jd }| | d S )Nr   )r   r*   rn   save_labelmer   r   r'   r(   r     s    z)AnnotationSet.save_labelme.<locals>._saverQ   r   r%   r   rR   r   r'   r   r(   r     s    zAnnotationSet.save_labelmec                   s@   t      jdd td fdd}| j||d d S )NTr   r;   c                    s"    t | jd }| | d S )Nr   )r   r*   rn   save_xmlr   r   r'   r(   r     s    z%AnnotationSet.save_xml.<locals>._saverQ   r   r   r'   r   r(   r     s    zAnnotationSet.save_xmlc                C   s   | j ||d d S r   r   r%   r   rR   r'   r'   r(   save_pascal_voc  s    zAnnotationSet.save_pascal_vocc                C   s   | j ||d d S r   r   r   r'   r'   r(   save_imagenet  s    zAnnotationSet.save_imagenetr   imageid_to_idauto_idsrR   zdict[str, int])r   r   r   rR   r+   c                   s2  |d ur d urn~| j d urP| jd urPdd | j  D }dd | j D  n@|rdd tt|  D }dd tt| jD  ntdg }d}t| d| d	D ]X}|j	D ]L}dd |j
 |j|jg ||j |d
}	|jr|j|	d< ||	 |d7 }qq fdd| D }
dd | D }|
||dS )Nc                 S   s   i | ]\}}||qS r'   r'   rG   kvr'   r'   r(   r     rJ   z)AnnotationSet.to_coco.<locals>.<dictcomp>c                 S   s   i | ]\}}||qS r'   r'   r   r'   r'   r(   r     rJ   c                 S   s   i | ]\}}||qS r'   r'   )rG   ilr'   r'   r(   r     rJ   c                 S   s   i | ]\}}||qS r'   r'   )rG   r   Zimr'   r'   r(   r     rJ   a  For COCO, mappings from labels and image ids to integer ids are required. They can be provided either by argument or automatically by the `AnnotationSet` instance if it was created with `AnnotationSet.from_coco()` or `AnnotationSet.from_coco_results()`. You can also set `auto_ids` to True to automatically create image and label ids (warning: this could cause unexpected compatibility issues with other COCO datasets).r   r   r   )Ziscrowdignorer*   r   areaZsegmentationr   r   r   r   c                    s&   g | ]} |j  |j |j|jd qS ))r   	file_namewidthheight)r*   Zimage_widthZimage_height)rG   ar   r'   r(   
<listcomp>8  s   z)AnnotationSet.to_coco.<locals>.<listcomp>c                 S   s   g | ]\}}d ||dqS )none)Zsupercategoryr   ro   r'   )rG   r   r   r'   r'   r(   r  B  s   )r   r    r   )r#   r$   r6   	enumeratesortedrP   r<   
ValueErrorr   rE   r*   Zltwhr   rM   Zis_detectionr   append)r%   r   r   r   rR   r    Zann_id_countr&   boxZbox_annotationr   r   r'   r  r(   to_coco  sF    	




zAnnotationSet.to_coco)rs   r   r   r   rR   c                C   s   t |  }|jdkr$|d}|jdks>J d| d| j||||d}t|d }tj||dd W d    n1 s0    Y  d S )	Nr   r   Path '' suffix should be '.json'.r   wF)fp	allow_nan)	r   r\   r]   r   rn   r  r   r   dump)r%   rs   r   r   r   rR   r   r   r'   r'   r(   	save_cocoI  s    	

zAnnotationSet.save_coco)rs   rR   c             
   C   s4  t |  }|jdkr$|d}|jdks>J d| dd}t|ddd}tj||dd}|  t	| d	| d
D ]}|j
}|j}|d u rtd|jD ]l}	|	j}
d|
v rtd|
 dtj|	j|d\}}}}||
||||d}|	jd ur|	j|d< || qqzW d    n1 s&0    Y  d S )Nr   r   r  z' suffix should be '.csv'.)r   ZSourcer   r   r   r   r   r   Z
IsOccludedZIsTruncatedZ	IsGroupOfZIsDepictionZIsInsider  r   )
fieldnamesrestvalr   r   zThe image size should be present in the annotation for `save_openimage`. One should parse the annotations specifying the image folder or populate the `image_size` attribute.,zThe box label 'a'  ' contains the character ',' which is the same as the separtor character used for BoundingBox representation in OpenImage format (CSV). This will corrupt the saved annotation file and likely make it unreadable. Use another character in the label name, e.g. use and underscore instead of a comma.)r   size)r   r   r   r   r   r   r   )r   r\   r]   r   rn   r   r   
DictWriterwriteheaderr   r*   rm   r  rE   rM   r   Z
abs_to_relZltrbr   writerow)r%   rs   rR   fieldsr   writerr&   r*   rm   r
  rM   ZxminZyminZxmaxZymaxr   r'   r'   r(   save_openimagec  sD    



	
zAnnotationSet.save_openimage)rR   r+   c                C   s:   t tjddd}t|| d|d}td}|| |S )Nr7   c                 S   s   |   S r3   )to_cvatr;   r'   r'   r(   _create_node  s    z+AnnotationSet.to_cvat.<locals>._create_noder   rV   r    )r   r   Elementr   extend)r%   rR   r  Z	sub_nodesnoder'   r'   r(   r    s
    

zAnnotationSet.to_cvatc                C   s   t |  }|jdkr$|d}|jdks>J d| d| j|d}tj|dd}t|d}|	| W d    n1 s0    Y  d S )	Nr   r   r  z' suffix should be '.xml'.rQ   unicode)encodingr  )
r   r\   r]   r   rn   r  r   tostringr   write)r%   rs   rR   r   r   r'   r'   r(   	save_cvat  s    

zAnnotationSet.save_cvat)r   r   rR   )rc   r   r   rR   r+   c          	      C   sJ   i }t | d| dD ]0}|j|||d}|d  |d  }|||< q|S )Nr   r   )rc   r   r   filenamer  )r   to_via_json)	r%   rc   r   r   rR   outputr&   Zann_dictkeyr'   r'   r(   r(    s    
zAnnotationSet.to_via_json)rs   rc   r   r   rR   c                C   s   t |  }|jdkr$|d}|jdks>J d| d| j||||d}t|d}tj||d W d    n1 s~0    Y  d S )Nr   r   r  r  )rc   r   r   rR   r  )r  )	r   r\   r]   r   rn   r(  r   r   r  )r%   rs   rc   r   r   rR   r)  r   r'   r'   r(   save_via_json  s    	

zAnnotationSet.save_via_jsonzdict[str, str])rs   r+   c                 C   s*   t |   } dd t|   D S )zParse .names file.

        Parameters:
        - path: the path to the .names file.

        Returns:
        - A dictionary mapping label number with label names.c                 S   s   i | ]\}}t ||qS r'   r   )rG   r   r   r'   r'   r(   r     rJ   z2AnnotationSet.parse_names_file.<locals>.<dictcomp>)r   r\   r]   r  	read_text
splitlines)rs   r'   r'   r(   parse_names_file  s    
zAnnotationSet.parse_names_filec                 C   sX   t |   } |  ,}tj|dd}dd |D W  d    S 1 sJ0    Y  d S )Nr   ZDisplayName)r  c                 S   s   i | ]}|d  |d qS r/  r'   )rG   r   r'   r'   r(   r     rJ   z0AnnotationSet.parse_mid_file.<locals>.<dictcomp>)r   r\   r]   r   r   r   )rs   r   r   r'   r'   r(   parse_mid_file  s    
zAnnotationSet.parse_mid_filec                C   s,  ddl m} ddlm} tt}tt}t| d| dD ]`}|jD ]}||j  d7  < qB|	 }|D ]}	||	  d7  < qft
|dkr8|d  d7  < q8t| }
t
| }|dd	d
}|jddd |jd| dd |jd|
 dd t| D ]&}	||	 }||	 }||	| |  q|| dS )z
        Print in the console a synthetic view of the dataset annotations (distribution of
        bounding boxes and images by label).
        r   )print)TableZStatsr   r   z<empty_image>zDatabase StatsT)titleZshow_footerZLabelZTotal)footerZImagesright)r4  ZjustifyZBoxesN)Zrichr1  Z
rich.tabler2  r   r   r   rE   rM   rP   r0   rK   r4   Z
add_columnr  r8   Zadd_row)r%   rR   Zrprintr2  Zbox_by_labelZim_by_labelr&   r
  labelsrM   Ztot_boxZtot_imtableZnb_imZnb_boxr'   r'   r(   
show_stats  s.    
zAnnotationSet.show_statsc                 C   s   d| j  dS )NzAnnotationSet(annotations: )r,   r1   r'   r'   r(   __repr__,  s    zAnnotationSet.__repr__)N)Q__name__
__module____qualname____doc__r
   r   r   r)   r   r.   r/   r   r2   r5   r6   boolr:   r"   r?   rA   rB   r	   rD   propertyr<   r   r   rF   rL   rP   staticmethodr   r   rX   r   r   ra   r   ZLTRBrq   ry   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   dictr  r  r  r   r  r  r&  r(  r+  r.  r0  r8  r:  r'   r'   r'   r(   r       s   


	L7.50*	"	

FE
&r   )+r   r   xml.etree.ElementTreeetreeElementTreer   collectionsr   pathlibr   typingr   r   r   r   r   r	   r
   r   r   warningsr   r   r&   r   Zatomicr   Zboundingboxr   r   errorsr   r   Z
file_utilsr   r   Zimage_utilsr   r   Zthread_utilsr   r   r   r'   r'   r'   r(   <module>   s    ,