§
    >²¸jÇ  ã                  ód   — 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Zd dl	m
Z
  G d„ d¦  «        ZdS )é    )ÚannotationsN)ÚAny)Ú
Detectionsc                  ó”   — e Zd ZdZd!d"d„Zd#d„Zd$d„Zd%d„Zed&d„¦   «         Z	d%d„Z
ed'd„¦   «         Ze	 d(d)d„¦   «         Z	 d(d*d „ZdS )+ÚJSONSinkaÖ  
    A utility class for saving detection data to a JSON file. This class is designed to
    efficiently serialize detection objects into a JSON format, allowing for the
    inclusion of bounding box coordinates and additional attributes like `confidence`,
    `class_id`, and `tracker_id`.

    !!! tip

        JSONSink 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.
        NumPy scalars (e.g. ``np.int64``, ``np.float32``) are serialized as
        JSON numbers; NumPy arrays are serialized as JSON arrays.

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

    Example:
        ```python
        import supervision as sv
        from rfdetr import RFDETRMedium

        model = RFDETRMedium()
        json_sink = sv.JSONSink(<RESULT_JSON_FILE_PATH>)
        frames_generator = sv.get_video_frames_generator("<SOURCE_VIDEO_PATH>")

        with json_sink as sink:
            for frame in frames_generator:
                detections = model.predict(frame[:, :, ::-1])
                sink.append(detections, custom_data={"<CUSTOM_LABEL>":"<CUSTOM_DATA>"})
        ```
    úoutput.jsonÚ	file_nameÚstrÚreturnÚNonec                ó0   — || _         d| _        g | _        dS )zt
        Initialize the JSONSink instance.

        Args:
            file_name: The name of the JSON file.
        N)r	   ÚfileÚdata)Úselfr	   s     úu/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/supervision/detection/tools/json_sink.pyÚ__init__zJSONSink.__init__3   s   € ð #ˆŒØ-1ˆŒ	Ø*,ˆŒ	ˆ	ˆ	ó    c                ó.   — |                       ¦   «          | S ©N)Úopen©r   s    r   Ú	__enter__zJSONSink.__enter__>   s   € Ø�	Š	‰ŒˆØˆr   Úexc_typeútype | NoneÚexc_valúException | NoneÚexc_tbú
Any | Nonec                ó.   — |                       ¦   «          d S r   )Úwrite_and_close)r   r   r   r   s       r   Ú__exit__zJSONSink.__exit__B   s   € ð 	×ÒÑÔÐÐÐr   c                óú   — t           j                             | j        ¦  «        }|r3t           j                             |¦  «        st          j        |¦  «         t          | j        d¦  «        | _        g | _        dS )z1
        Open the JSON file for writing.
        ÚwN)	ÚosÚpathÚdirnamer	   ÚexistsÚmakedirsr   r   r   )r   Úparent_directorys     r   r   zJSONSink.openJ   sg   € õ œ7Ÿ?š?¨4¬>Ñ:Ô:ÐØð 	*¥B¤G§N¢NÐ3CÑ$DÔ$Dð 	*ÝŒKÐ(Ñ)Ô)Ð)å˜œ¨Ñ-Ô-ˆŒ	ØˆŒ	ˆ	ˆ	r   Úvaluer   c                ó  — t          | t          j        ¦  «        r|                      ¦   «         S t          | t          j        ¦  «        r|                      ¦   «         S t          dt          | ¦  «        j        › d�¦  «        ‚)a  Return a JSON-serializable equivalent of a NumPy scalar or array.

        Called as the ``default`` hook by :func:`json.dump`. Converts
        :class:`numpy.generic` scalars via ``.item()`` and
        :class:`numpy.ndarray` instances via ``.tolist()``.

        Args:
            value: Object the standard JSON encoder could not serialize.

        Returns:
            A Python scalar or nested list equivalent of ``value``.

        Raises:
            TypeError: If ``value`` is neither a NumPy scalar nor an ndarray.
        zObject of type z is not JSON serializable)	Ú
isinstanceÚnpÚgenericÚitemÚndarrayÚtolistÚ	TypeErrorÚtypeÚ__name__)r*   s    r   Ú_json_defaultzJSONSink._json_defaultU   sq   € õ" �e�RœZÑ(Ô(ð 	 Ø—:’:‘<”<ÐÝ�e�RœZÑ(Ô(ð 	"Ø—<’<‘>”>Ð!ÝØM�d 5™kœkÔ2ÐMÐMÐMñ
ô 
ð 	
r   c                óà   — | j         rf	 t          j        | j        | j         dt          j        ¬¦  «         | j                              ¦   «          dS # | j                              ¦   «          w xY wdS )z0
        Write and close the JSON file.
        é   )ÚindentÚdefaultN)r   ÚjsonÚdumpr   r   r5   Úcloser   s    r   r    zJSONSink.write_and_closen   sx   € ð Œ9ð 	"ð"Ý”	Ø”I˜tœy°½HÔ<Rðñ ô ð ð ”	—’Ñ!Ô!Ð!Ð!Ð!ø�”	—’Ñ!Ô!Ð!Ð!øøøð	"ð 	"s   ‰,A ÁA+Ú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   )r,   r-   r0   ÚndimÚlenÚlistÚtuple)r*   r=   r?   s      r   Ú_slice_valuezJSONSink._slice_valuez   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 �]†}t          | j        |         d         ¦  «        t          | j        |         d         ¦  «        t          | j        |         d         ¦  «        t          | 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                               |||¦  «        ||<   Œ%|                     |¦  «         �Œˆ|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   é   é   é   NÚ )Úx_minÚy_minÚx_maxÚy_maxÚclass_idÚ
confidenceÚ
tracker_idr   )rB   ÚxyxyÚrangeÚfloatrS   r>   rT   rU   Úhasattrr   Úitemsr   rE   Úappend)rF   rG   Úparsed_rowsr?   r=   ÚrowÚkeyr*   s           r   Úparse_detection_datazJSONSink.parse_detection_data”   s·  € ð, ˆÝ�
”Ñ Ô ˆÝ�q‘”ð 	$ñ 	$ˆAå˜zœ¨qÔ1°!Ô4Ñ5Ô5Ý˜zœ¨qÔ1°!Ô4Ñ5Ô5Ý˜zœ¨qÔ1°!Ô4Ñ5Ô5Ý˜zœ¨qÔ1°!Ô4Ñ5Ô5àÔ&Ð.ð ˜Bå˜Ô,¨QÔ/Ñ0Ô0àÔ(Ð0ð !˜bå˜:Ô0°Ô3Ñ4Ô4àÔ(Ð0ð !˜bå˜Ô.¨qÔ1Ñ2Ô2ðð ˆCõ  �z 6Ñ*Ô*ð BØ",¤/×"7Ò"7Ñ"9Ô"9ð Bð B‘J�C˜Ý'×4Ò4°U¸A¸qÑAÔA�C˜‘H�Hàð BØ"-×"3Ò"3Ñ"5Ô"5ð Bð B‘J�C˜Ý'×4Ò4°U¸A¸qÑAÔA�C˜‘H�Hà×Ò˜sÑ#Ô#Ð#Ñ#ØÐr   c                óp   — t                                ||¦  «        }| j                             |¦  «         dS )aÝ  
        Append detection data to the JSON file.

        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.
        N)r   r_   r   Úextend)r   rF   rG   r\   s       r   r[   zJSONSink.appendÈ   s5   € õ ×3Ò3°JÀÑLÔLˆØŒ	×Ò˜Ñ%Ô%Ð%Ð%Ð%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>   r?   r>   r   r   r   )rF   r   rG   rH   r   rI   )rF   r   rG   rH   r   r   )r4   Ú
__module__Ú__qualname__Ú__doc__r   r   r!   r   Ústaticmethodr5   r    rE   r_   r[   © r   r   r   r      s  € € € € € ð#ð #ðJ	-ð 	-ð 	-ð 	-ð 	-ðð ð ð ðð ð ð ð	ð 	ð 	ð 	ð ð
ð 
ð 
ñ „\ð
ð0
"ð 
"ð 
"ð 
"ð ðð ð ñ „\ðð2 àEIð1ð 1ð 1ð 1ñ „\ð1ðh LPð&ð &ð &ð &ð &ð &ð &r   r   )Ú
__future__r   Úior:   r$   Útypingr   Únumpyr-   Úsupervision.detection.corer   r   rf   r   r   ú<module>rl      sž   ðØ "Ð "Ð "Ð "Ð "Ð "à 	€	€	€	Ø €€€Ø 	€	€	€	Ø Ð Ð Ð Ð Ð à Ð Ð Ð à 1Ð 1Ð 1Ð 1Ð 1Ð 1ðJ&ð J&ð J&ð J&ð J&ñ J&ô J&ð J&ð J&ð J&r   