
    ^j/                    8   d dl mZ d dlZd dlmZ d dlmZmZ d dlZd dl	Z
d dlmZ d dlmZ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 	 d	 	 	 	 	 	 	 ddZ	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ	 d	 	 	 	 	 	 	 ddZ	 d	 	 	 	 	 	 	 	 	 ddZddZ ddZ!ddZ"y)    )annotationsN)Path)Element
SubElement)parsetostring)parseString)approximate_mask_with_polygons)
Detections)polygon_to_maskpolygon_to_xyxy)list_files_with_extensionsc                z   t        d      }t        |d      }||_        | dz   } t        |d      }t        |d      }t        t	        | d               |_        t        |d      }t        t	        | d               |_        t        |d      }t        t	        | d	               |_        t        |d
      }	t        t	        | d               |	_        |i|dz   }t        |d      }
t        |d      D ]H  \  }}|\  }}t        |
d|       }t        |      |_        t        |
d|       }t        |      |_        J |S )a  Build a Pascal VOC ``<object>`` XML element for one detection.

    Coordinates are converted to 1-indexed Pascal VOC convention before writing.
    The input arrays are never mutated; new arrays are allocated for the offset.

    Args:
        xyxy: Bounding box in zero-indexed pixel coordinates ``[x1, y1, x2, y2]``.
            Shape ``(4,)``.
        name: Class label string written to the ``<name>`` child element.
        polygon: Optional segmentation polygon in zero-indexed pixel coordinates.
            Shape ``(N, 2)``.

    Returns:
        An XML ``Element`` rooted at ``<object>`` containing ``<name>``,
        ``<bndbox>``, and optionally ``<polygon>`` children.

    Examples:
        >>> import numpy as np
        >>> from supervision.dataset.formats.pascal_voc import object_to_pascal_voc
        >>> elem = object_to_pascal_voc(np.array([0, 0, 9, 9]), name="cat")
        >>> elem.find("bndbox/xmin").text
        '1'
        >>> elem.find("bndbox/xmax").text
        '10'
    objectname   bndboxxminr   yminxmax   ymax   polygon)startxy)r   r   textstrint	enumerate)xyxyr   r   rootobject_namer   r   r   r   r   object_polygonindexpointx_coordinatey_coordinater   r   s                    q/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/supervision/dataset/formats/pascal_voc.pyobject_to_pascal_vocr+      s;   < 8DT6*KK !8Dh'Fff%DCQL!DIff%DCQL!DIff%DCQL!DIff%DCQL!DIA+#D)4%gQ7 	'LE5).&L,>Qug;7A&AF>Qug;7A&AF	' K    c                f   |\  }}}	t        d      }
t        |
d      }d|_        t        |
d      }||_        t        |
d      }t        |d      }d|_        t        |
d      }t        |d	      }t        |      |_        t        |d
      }t        |      |_        t        |d      }t        |	      |_        t        |
d      }d|_        | D ]  \  }}}}}}|t	        d      t        |t        t        j                  f      st	        dt        |      d      ||   }|Bt        ||||      }|D ]-  }t        |      }t        |||      }|
j                  |       / t        ||      }|
j                  |        t        t        t        |
            j!                  d            }|S )a  
    Converts Detections object to Pascal VOC XML format.

    Args:
        detections: A Detections object containing bounding boxes,
            class ids, and other relevant information.
        classes: A list of class names corresponding to the
            class ids in the Detections object.
        filename: The name of the image file associated with the detections.
        image_shape: The shape of the image
            file associated with the detections.
        min_image_area_percentage: Minimum detection area
            relative to area of image associated with it.
        max_image_area_percentage: Maximum detection area
            relative to area of image associated with it.
        approximation_percentage: The percentage of
            polygon points to be removed from the input polygon, in the range [0, 1).
    Returns:
        An XML string in Pascal VOC format representing the detections.

    Note:
        ``detections`` is never mutated by this function; the source ``xyxy``
        array is unchanged after the call. The function is therefore safe to
        call multiple times on the same ``Detections`` object.
    
annotationfolderVOCfilenamesourcedatabasezroboflow.aisizewidthheightdepth	segmented0z7Detections must include class_id for Pascal VOC export.zBDetections class_id must be an integer for Pascal VOC export, got .)maskmin_image_area_percentagemax_image_area_percentageapproximation_percentage)r   )r"   r   r   )r"   r   z  )indent)r   r   r   r   
ValueError
isinstancer    npintegertyper
   r   r+   appendr	   r   toprettyxml)
detectionsclassesr1   image_shaper<   r=   r>   r6   r5   r7   r.   r/   	file_namer2   r3   r4   whdr8   r"   r;   _class_idr   polygonsr   next_object
xml_strings                                r*   detections_to_pascal_vocrS   T   s   D 'FE5 &J 
H-FFK :z2IIN 
H-F&*-H!HM j&)D4!AZAF4"A[AF4!AZAF :{3IIN *4 +%dAxAVWW(S"**$56H~(+  x 5*C*C)A	H $ /&w72D' !!+./ /DtDKk*1+6 [*!56BB$BOPJr,   c                <   t        | g d      D cg c]  }t        |       }}g }i }|D ]  }t        |      j                  }t        j
                  j                  || d      }	t        j
                  j                  |	      st        j                         ||<   rt        |	      }
|
j                         }t        j                  |      }|t        d|       |j                  d   |j                  d   f}t!        ||||      \  }}|||<    |||fS c c}w )a  
    Loads PASCAL VOC XML annotations and returns the image name,
        a Detections instance, and a list of class names.

    Args:
        images_directory_path: The path to the directory containing the images.
        annotations_directory_path: The path to the directory containing the
            PASCAL VOC annotation files.
        force_masks: If True, forces masks to be loaded for all
            annotations, regardless of whether they are present.

    Returns:
        A tuple with a list
            of class names, a list of paths to images, and a dictionary with image
            paths as keys and corresponding Detections instances as values.
    )jpgjpegpng)	directory
extensionsz.xmlz Could not read image from path: r   r   )r   r   r   stemospathjoinexistsr   emptyr   getrootcv2imreadr@   shapedetections_from_xml_obj)images_directory_pathannotations_directory_pathforce_masksr\   image_pathsrH   r   
image_path
image_stemannotation_pathtreer#   imageresolution_whr.   s                  r*   load_pascal_voc_annotationsro      s+   0 /+8N
 	D	K  GK! -
*%**
'',,'Aj\QUCVWww~~o.&0&6&6&8K
#_%||~

:&=?
|LMMQQ85'=+

G #-J#-& K,,;s   Dc                   g }g }g }|xs! t        d | j                  d      D              }|dd }| j                  d      D ]*  }	t        |	d      }
|j                  |
       |	j	                  d      }|t        d      t        t        |d            }t        t        |d            }t        t        |d	            }t        t        |d
            }|j                  ||||g       t        j                  |d   |d   ft              }|	j                  d      D ]7  }t        |      }|dz  }t        ||      }||j                  t              z  }9 |s|j                  |       - |r&t        j                  |t        j                        }n%t        j                  dt        j                        }|dz  }t!        |      D ]  }||vs|j                  |        t        j                  |D 
cg c]  }
|j#                  |
       c}
      }t%        ||rt        j                  |t              nd|      }||fS c c}
w )aB  
    Converts an XML object in Pascal VOC format to a Detections object.
    Expected XML format:
    <annotation>
        ...
        <object>
            <name>dog</name>
            <bndbox>
                <xmin>48</xmin>
                <ymin>240</ymin>
                <xmax>195</xmax>
                <ymax>371</ymax>
            </bndbox>
            <polygon>
                <x1>48</x1>
                <y1>240</y1>
                <x2>195</x2>
                <y2>240</y2>
                <x3>195</x3>
                <y3>371</y3>
                <x4>48</x4>
                <y4>371</y4>
            </polygon>
        </object>
    </annotation>

    Returns:
        A tuple containing a Detections object and an
            updated list of class names, extended with the class names
            from the XML object.
    c              3  2   K   | ]  }t        |        y wN)_with_poly_mask).0objs     r*   	<genexpr>z*detections_from_xml_obj.<locals>.<genexpr>  s      $!$$s   r   Nr   r   z(Missing bndbox in Pascal VOC annotation.r   r   r   r   r   r   dtyper   )r   rn   )r      )r"   r;   rO   )anyfindall_get_required_textrE   findr@   r    rB   zerosboolparse_polygon_pointsr   astypearrayfloat32r_   setr&   r   )r#   rH   rn   rg   r"   class_namesmasks
with_masksextended_classesru   
class_namebboxx1y1x2y2object_maskpolygon_elementr   mask_from_polygonxyxy_arrkrO   r.   s                           r*   rd   rd      sD   J DK)+E  $(,X(>$ !J qz||H% &'V4
:&xx!<GHH#D&12#D&12#D&12#D&12RR$%-/XX1}Q/0.
  #{{95 		:O*?;GqLG /+! ,33D99K		: LL%;&@ 88D

388F"**5 MH '$$##A&' xx>IJ
			
	+JH ,6RXXe4(DJ ''' 	Ks   ;I	c                (    | j                  d      d uS )Nr   )r}   )ru   s    r*   rs   rs   O  s    88Id**r,   c           	     B   g }| j                  d      D ]=  }|j                  t        d      |j                  t	        |j                               ? t        j                  t        dt        |      d      D cg c]  }||   ||dz      f c}t              S c c}w )Nz.//*z/Missing polygon coordinate value in Pascal VOC.r   r   r   rw   )	r{   r   r@   rE   r    rB   r   rangelen)r   coordinatescoordis       r*   r   r   S  s    K( ,::NOO3uzz?+, 887<QK@PRS7TU!+a.+a!e,	-U Us   ;Bc                v    | j                  |      }||j                  t        d| d      |j                  S )Nz	Missing 'z' in Pascal VOC annotation.)r}   r   r@   )elementtagchilds      r*   r|   r|   _  s=    LLE}

*9SE)DEFF::r,   rr   )r"   znpt.NDArray[np.number]r   r   r   znpt.NDArray[np.number] | Nonereturnr   )g        g      ?g      ?)rG   r   rH   	list[str]r1   r   rI   ztuple[int, int, int]r<   floatr=   r   r>   r   r   r   )F)re   r   rf   r   rg   r   r   z2tuple[list[str], list[str], dict[str, Detections]])
r#   r   rH   r   rn   ztuple[int, int]rg   r   r   ztuple[Detections, list[str]])ru   r   r   r   )r   r   r   znpt.NDArray[np.int_])r   r   r   r   r   r   )#
__future__r   r[   pathlibr   xml.etree.ElementTreer   r   ra   numpyrB   numpy.typingtypingnptdefusedxml.ElementTreer   r   defusedxml.minidomr	   supervision.dataset.utilsr
   supervision.detection.corer   &supervision.detection.utils.convertersr   r   supervision.utils.filer   r+   rS   ro   rd   rs   r   r|    r,   r*   <module>r      s>   " 	  5 
   2 * D 1 S = .2>
 >
> +> 	>L (+'*&*^^^ ^ &	^
  %^  %^ $^ 	^H 3-3- #3- 3- 8	3-t 	a(
a(a( #a( 	a(
 "a(H+	r,   