§
    >²¸jò'  ã                  óº   — 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m	Z	 d dl
Zd dlmZ d dlmZ  ee¦  «        Zg d¢Z G d„ d	e	¦  «        Z G d
„ d¦  «        ZdS )é    )ÚannotationsN)ÚIterable)ÚAnyÚProtocol)Ú
Detections)Ú_get_logger©Úx_minÚy_minÚx_maxÚy_maxÚclass_idÚ
confidenceÚ
tracker_idc                  ó   — e Zd Zdd„ZdS )ÚWriterProtocolÚrowúIterable[Any]Úreturnr   c                ó   — d S ©N© )Úselfr   s     út/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/supervision/detection/tools/csv_sink.pyÚwriterowzWriterProtocol.writerow   s   € € € ó    N)r   r   r   r   )Ú__name__Ú
__module__Ú__qualname__r   r   r   r   r   r      s   € € € € € Ø6Ð6Ð6Ð6Ð6Ð6r   r   c                  ó˜   — e Zd ZdZd"d#d„Zd$d„Zd%d„Zd&d„Zd&d„Ze	d'd„¦   «         Z
e		 d(d)d„¦   «         Z	 d(d*d„Ze		 d(d+d!„¦   «         ZdS ),ÚCSVSinkaf  
    A utility class for saving detection data to a CSV file. This class is designed to
    efficiently serialize detection objects into a CSV format, allowing for the
    inclusion of bounding box coordinates and additional attributes like `confidence`,
    `class_id`, and `tracker_id`.

    !!! tip

        CSVSink allows passing custom data alongside detection fields, providing
        flexibility for logging various types of information.
        When a NumPy array, list, or tuple value in custom_data (or
        detections.data) has the same length as the detection count, each
        element is written to the corresponding detection row; any other value
        is broadcast to all rows.

    Args:
        file_name: The name of the CSV file where the detections will be stored.
            Defaults to 'output.csv'.

    Example:
        ```pycon
        >>> import supervision as sv
        >>> import numpy as np
        >>> import tempfile
        >>> import os
        >>> # Create synthetic detections
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[10, 20, 30, 40], [50, 60, 70, 80]]),
        ...     confidence=np.array([0.9, 0.8]),
        ...     class_id=np.array([0, 1])
        ... )
        >>> # Use temporary file
        >>> temp_file = tempfile.NamedTemporaryFile(
        ...     mode='w', suffix='.csv', delete=False
        ... )
        >>> temp_file.close()
        >>> csv_sink = sv.CSVSink(temp_file.name)
        >>> with csv_sink as sink:
        ...     sink.append(detections, custom_data={'frame': 0})
        >>> os.unlink(temp_file.name)  # Clean up

        ```
    ú
output.csvÚ	file_nameÚstrr   ÚNonec                óZ   — || _         d| _        d| _        d| _        g | _        g | _        dS )zr
        Initialize the CSVSink instance.

        Args:
            file_name: The name of the CSV file.
        NF)r#   ÚfileÚwriterÚheader_writtenÚfield_namesÚdeferred_field_names)r   r#   s     r   Ú__init__zCSVSink.__init__L   s7   € ð #ˆŒØ-1ˆŒ	Ø-1ˆŒØ#ˆÔØ&(ˆÔØ/1ˆÔ!Ð!Ð!r   c                ó.   — |                       ¦   «          | S r   )Úopen©r   s    r   Ú	__enter__zCSVSink.__enter__Z   s   € Ø�	Š	‰ŒˆØˆr   Úexc_typeútype | NoneÚexc_valúException | NoneÚexc_tbú
Any | Nonec                ó.   — |                       ¦   «          d S r   )Úclose)r   r1   r3   r5   s       r   Ú__exit__zCSVSink.__exit__^   s   € ð 	�
Š
‰Œˆˆˆr   c                óV  — t           j                             | j        ¦  «        }|r3t           j                             |¦  «        st          j        |¦  «         t          | j        dd¬¦  «        | _        t          j	        | j        ¦  «        | _	        d| _
        g | _        g | _        dS )z0
        Open the CSV file for writing.
        ÚwÚ )ÚnewlineFN)ÚosÚpathÚdirnamer#   ÚexistsÚmakedirsr.   r'   Úcsvr(   r)   r*   r+   )r   Úparent_directorys     r   r.   zCSVSink.openf   s’   € õ œ7Ÿ?š?¨4¬>Ñ:Ô:ÐØð 	*¥B¤G§N¢NÐ3CÑ$DÔ$Dð 	*ÝŒKÐ(Ñ)Ô)Ð)å˜œ¨°bÐ9Ñ9Ô9ˆŒ	Ý”j ¤Ñ+Ô+ˆŒØ#ˆÔØˆÔØ$&ˆÔ!Ð!Ð!r   c                ó.  — | j         �| j         j        rdS 	 | j        s@| j        r9| j        r2| j        | _        | j                             | j        ¦  «         d| _        | j                              ¦   «          dS # | j                              ¦   «          w xY w)a8  
        Close the CSV file.

        When every appended batch was empty no header has been written yet, so
        the schema remembered from the first such batch is emitted here. This
        keeps a run that never detected anything readable as an empty table
        rather than as a zero-byte file.
        NT)r'   Úclosedr)   r+   r(   r*   r   r8   r/   s    r   r8   zCSVSink.closet   sš   € ð Œ9Ð ¤	Ô 0ÐØˆFð
	ØÔ&ð +¨4Ô+Dð +ÈÌð +Ø#'Ô#<�Ô Ø”×$Ò$ TÔ%5Ñ6Ô6Ð6Ø&*�Ô#àŒI�OŠOÑÔÐÐÐøˆDŒI�OŠOÑÔÐÐøøøs   —AA9 Á9BÚvaluer   ÚiÚintÚnc                óø   — t          | t          j        ¦  «        r(| j        dk    rt	          | ¦  «        |k    r| |         n| S t          | t
          t          f¦  «        rt	          | ¦  «        |k    r| |         S | S )a€  
        Return the i-th element when the value stores per-detection data.

        Dispatch rules:
            - np.ndarray with ndim == 0: return as-is for broadcasting
            - np.ndarray with len equal to n: return value[i]
            - list or tuple with len equal to n: return value[i]
            - any other type: return as-is for broadcasting

        Args:
            value: Custom-data field value.
            i: Zero-based detection index.
            n: Total number of detections.

        Returns:
            Element at position i if value is a per-detection sequence,
            otherwise value unchanged.
        r   )Ú
isinstanceÚnpÚndarrayÚndimÚlenÚlistÚtuple)rG   rH   rJ   s      r   Ú_slice_valuezCSVSink._slice_value‹   sq   € õ( �e�RœZÑ(Ô(ð 	MØ$œz¨Aš~˜~µ#°e±*´*À²/°/�5˜”8�8ÀuÐLÝ�e�d¥E˜]Ñ+Ô+ð 	µ°E±
´
¸a²°Ø˜”8ˆOØˆr   NÚ
detectionsr   Úcustom_dataúdict[str, Any] | Noneúlist[dict[str, Any]]c                óø  — g }t          | j        ¦  «        }t          |¦  «        D �]R}| j        |         d         | j        |         d         | j        |         d         | j        |         d         | j        €dnt	          | j        |         ¦  «        | j        €dnt	          | j        |         ¦  «        | j        €dnt	          | j        |         ¦  «        dœ}t          | d¦  «        r>| j         	                    ¦   «         D ]$\  }}t                               |||¦  «        ||<   Œ%|r9| 	                    ¦   «         D ]$\  }}t                               |||¦  «        ||<   Œ%|                     |¦  «         �ŒT|S )	aY  
        Convert detections and optional custom data into per-detection rows.

        Builds one dictionary per detection containing bounding box coordinates,
        detection attributes, and any values from ``detections.data`` or
        ``custom_data``. NumPy array, list, and tuple values in
        ``custom_data`` with length equal to ``len(detections.xyxy)`` are
        sliced one element per row; all other values are broadcast to every row.

        Args:
            detections: Detection data to serialize into row dictionaries.
            custom_data: Optional extra fields to include in each row.

        Returns:
            A list of dictionaries, one per detection, containing ``xyxy``
            coordinates, ``class_id``, ``confidence``, ``tracker_id``, and any
            values from ``detections.data`` or ``custom_data``.
        r   é   é   é   Nr<   r	   Údata)rP   ÚxyxyÚranger   r$   r   r   Úhasattrr\   Úitemsr!   rS   Úappend)rT   rU   Úparsed_rowsrJ   rH   r   ÚkeyrG   s           r   Úparse_detection_datazCSVSink.parse_detection_data¥   s—  € ð, ˆÝ�
”Ñ Ô ˆÝ�q‘”ð 	$ñ 	$ˆAà#œ¨Ô+¨AÔ.Ø#œ¨Ô+¨AÔ.Ø#œ¨Ô+¨AÔ.Ø#œ¨Ô+¨AÔ.àÔ&Ð.ð ˜Bå˜Ô,¨QÔ/Ñ0Ô0àÔ(Ð0ð !˜bå˜Ô.¨qÔ1Ñ2Ô2àÔ(Ð0ð !˜bå˜Ô.¨qÔ1Ñ2Ô2ðð ˆCõ  �z 6Ñ*Ô*ð AØ",¤/×"7Ò"7Ñ"9Ô"9ð Að A‘J�C˜Ý&×3Ò3°E¸1¸aÑ@Ô@�C˜‘H�Hàð AØ"-×"3Ò"3Ñ"5Ô"5ð Að A‘J�C˜Ý&×3Ò3°E¸1¸aÑ@Ô@�C˜‘H�Hà×Ò˜sÑ#Ô#Ð#Ñ#ØÐr   c                ó  ‡— | j         st          d| j        › d�¦  «        ‚t                               ||¦  «        }t          |¦  «        dk    r| j        s| j        s|| _        dS | j        s(|| _        | j          	                    |¦  «         d| _        || j        k    r!t                               d| j        |¦  «         t                               ||¦  «        }|D ]-Š| j          	                    ˆfd„| j        D ¦   «         ¦  «         Œ.dS )a[  
        Append detection data to the CSV file.

        The CSV header is fixed by the first batch that actually contains
        detections; batches with no detections write nothing and leave the
        header undecided, so an empty first frame does not strip the columns
        of the frames that follow. While no populated batch has appeared, the
        schema of the first empty batch is the one ``close()`` falls back to.

        Args:
            detections: The detection data.
            custom_data: Custom data to include. Scalars, dictionaries, and
                other non-sequence values are broadcast to every detection in
                this batch. NumPy arrays, lists, and tuples with length equal
                to ``len(detections)`` are sliced per detection; other lists
                and tuples are broadcast unchanged.
        z Cannot append to CSV: The file 'z' is not open.r   NTz<Field names do not match the header. Expected: %s, given: %sc                ó<   •— g | ]}‰                      |d ¦  «        ‘ŒS )r<   )Úget)Ú.0Ú
field_namer   s     €r   ú
<listcomp>z"CSVSink.append.<locals>.<listcomp>  s'   ø€ ÐLÐLÐL¨Z�—’˜ RÑ(Ô(ÐLÐLÐLr   )r(   Ú	Exceptionr#   r!   Úparse_field_namesrP   r)   r+   r*   r   ÚloggerÚwarningrd   )r   rT   rU   r*   rb   r   s        @r   ra   zCSVSink.appendÙ   sG  ø€ ð( Œ{ð 	ÝØQ°4´>ÐQÐQÐQñô ð õ ×/Ò/°
¸KÑHÔHˆõ ˆz‰?Œ?˜aÒÐØÔ&ð 8¨tÔ/Hð 8Ø,7�Ô)ØˆFàÔ"ð 	'Ø*ˆDÔØŒK× Ò  Ñ-Ô-Ð-Ø"&ˆDÔà˜$Ô*Ò*Ð*Ý�NŠNØNØÔ Øñô ð õ ×2Ò2°:¸{ÑKÔKˆØð 	ð 	ˆCØŒK× Ò ØLÐLÐLÐL¸4Ô;KÐLÑLÔLñô ð ð ð	ð 	r   ú	list[str]c           
     óø   — |r!t          |                     ¦   «         ¦  «        nt          ¦   «         }t          |t          t          | di ¦  «                             ¦   «         ¦  «        z  ¦  «        }t          |z   S )Nr\   )ÚsetÚkeysÚsortedÚgetattrÚBASE_HEADER)rT   rU   Úcustom_keysÚdynamic_headers       r   rl   zCSVSink.parse_field_names  so   € ð 2=ÐG•c˜+×*Ò*Ñ,Ô,Ñ-Ô-Ð-Å#Á%Ä%ˆÝØ�#�g j°&¸"Ñ=Ô=×BÒBÑDÔDÑEÔEÑEñ
ô 
ˆõ ˜^Ñ+Ð+r   )r"   )r#   r$   r   r%   )r   r!   )r1   r2   r3   r4   r5   r6   r   r%   )r   r%   )rG   r   rH   rI   rJ   rI   r   r   r   )rT   r   rU   rV   r   rW   )rT   r   rU   rV   r   r%   )rT   r   rU   rV   r   ro   )r   r   r   Ú__doc__r,   r0   r9   r.   r8   ÚstaticmethodrS   rd   ra   rl   r   r   r   r!   r!      s  € € € € € ð*ð *ðX2ð 2ð 2ð 2ð 2ðð ð ð ðð ð ð ð'ð 'ð 'ð 'ðð ð ð ð. ðð ð ñ „\ðð2 àEIð1ð 1ð 1ð 1ñ „\ð1ðh LPð5ð 5ð 5ð 5ð 5ðn àEIð,ð ,ð ,ð ,ñ „\ð,ð ,ð ,r   r!   )Ú
__future__r   rC   Úior>   Úcollections.abcr   Útypingr   r   ÚnumpyrM   Úsupervision.detection.corer   Úsupervision.utils.loggerr   r   rm   ru   r   r!   r   r   r   ú<module>r�      s  ðØ "Ð "Ð "Ð "Ð "Ð "à 
€
€
€
Ø 	€	€	€	Ø 	€	€	€	Ø $Ð $Ð $Ð $Ð $Ð $Ø  Ð  Ð  Ð  Ð  Ð  Ð  Ð  à Ð Ð Ð à 1Ð 1Ð 1Ð 1Ð 1Ð 1Ø 0Ð 0Ð 0Ð 0Ð 0Ð 0à	ˆ�XÑ	Ô	€ðð ð €ð7ð 7ð 7ð 7ð 7�Xñ 7ô 7ð 7ðy,ð y,ð y,ð y,ð y,ñ y,ô y,ð y,ð y,ð y,r   