§
    >²¸jÞ0  ã                  óª   — d dl mZ d dlmZ d dlmZ d dlmZ d dlZ	d dl
mZ d dlmZ d dlmZ eeeegdf         Z G d„ d	¦  «        Z	 ddd„Zdd„ZdS )é    )Úannotations)ÚCallable)Úsuppress)ÚAnyN)ÚImage©Úcv2_to_pillowc                  óÀ   — e Zd ZdZ	 d0d1d
„Zd2d„Zd3d4d„Zd5d„Zed6d„¦   «         Z	d7d„Z
d8d„Zd9d„Zd7d„Zd:d„Zd7d „Zd;d#„Zd:d$„Zd<d&„Zd=d*„Zd7d+„Zd7d,„Zd6d-„Zd7d.„Zd/S )>ÚImageWindowuR	  Desktop image window backed by stdlib tkinter + pillow.

    Functional replacement for `cv2.imshow` / `cv2.waitKey` that works under
    `opencv-python-headless`. Requires tkinter (stdlib) and pillow (already a
    supervision dependency). Instantiation always succeeds; `show()` raises
    `ModuleNotFoundError` (No module named '_tkinter') on environments where
    `python3-tk` is absent â€” install with ``sudo apt-get install python3-tk``
    (Debian/Ubuntu) or ``brew install tcl-tk`` (macOS with Homebrew/pyenv)
    â€” and raises `tkinter.TclError` on headless servers where a display is
    unavailable.

    Differences from cv2:
        - `wait_key()` returns a tkinter keysym `str` (e.g. ``"q"``,
          ``"Return"``, ``"Escape"``) or ``None``, not an ``int``. Code
          relying on ``key == ord("q")`` or ``key & 0xFF == 27`` must be
          updated to ``key == "q"`` or ``key == "Escape"``.
        - Mouse callback signature is ``(x: int, y: int, event_type: str)``
          where ``event_type`` is ``"down"``, ``"up"``, or ``"move"``. This
          differs from cv2's ``(event: int, x, y, flags, param)`` â€” existing
          cv2 mouse callbacks are not compatible without modification.
        - Only left-button events are captured. Right-button clicks, scroll
          events, and modifier-key flags (Ctrl, Shift) have no equivalent.

    Args:
        title: Window title bar text.
        keep_aspect_ratio: If ``True`` (default), frames are scaled to fit
            inside the window while preserving aspect ratio (letterboxed). If
            ``False``, frames are stretched to fill the window exactly.

    Examples:
        ```python
        import supervision as sv

        window = sv.ImageWindow("preview")
        for frame in sv.get_video_frames_generator(source_path="video.mp4"):
            annotated = ...  # annotate frame
            window.show(annotated)
            if window.wait_key(delay_ms=1) == "q":
                break
        window.close()
        ```

        Context-manager form closes automatically:

        ```python
        import supervision as sv

        with sv.ImageWindow("preview") as window:
            for frame in sv.get_video_frames_generator(source_path="video.mp4"):
                window.show(frame)
                if window.wait_key(delay_ms=1) == "q":
                    break
        ```
    ÚsupervisionTÚtitleÚstrÚkeep_aspect_ratioÚboolÚreturnÚNonec                óØ   — || _         || _        d | _        d | _        d | _        d | _        d | _        g | _        d | _        d| _	        d| _
        d| _        d| _        d| _        d| _        d S ©Nr   ç      ð?ç        )r   r   Ú_mouse_callbackÚ_rootÚ_labelÚ_photoÚ
_key_eventÚ
_key_queueÚ
_pil_imageÚ_win_wÚ_win_hÚ_display_scale_xÚ_display_scale_yÚ_display_offset_xÚ_display_offset_y)Úselfr   r   s      ún/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/supervision/utils/image_window.pyÚ__init__zImageWindow.__init__H   sy   € ð ˆŒ
Ø!2ˆÔØ59ˆÔØˆŒ
ØˆŒØˆŒØ#ˆŒØ%'ˆŒØ.2ˆŒØˆŒØˆŒØ'*ˆÔØ'*ˆÔØ(+ˆÔØ(+ˆÔÐÐó    Úimageúnpt.NDArray[np.uint8]c                ó<  — |j         t          j        k    rt          d|j         › d�¦  «        ‚t	          |¦  «        | _        |                      ¦   «          |                      ¦   «          | j         	                    ¦   «          | j         
                    ¦   «          dS )u­  Display a BGR, grayscale, or BGRA frame in the window.

        The image is scaled to fit the current window dimensions. Aspect ratio is
        preserved unless `keep_aspect_ratio=False`. Resizing the window rescales live.
        Args:
            image: uint8 numpy array. Accepted shapes:
                - ``(H, W)`` â€” grayscale
                - ``(H, W, 3)`` â€” BGR (OpenCV convention; channels are swapped
                  to RGB before display)
                - ``(H, W, 4)`` â€” BGRA (channels reordered to RGBA)

        Raises:
            TypeError: If `image.dtype` is not `uint8`.
            ValueError: If `image` is not 2-D or 3-D with 3 or 4 channels.
        zimage must be uint8, got z<. Convert with image.astype(np.uint8) before calling show().N)ÚdtypeÚnpÚuint8Ú	TypeErrorÚ_bgr_to_pilr   Ú_ensure_windowÚ_update_displayr   Úupdate_idletasksÚupdate)r$   r(   s     r%   ÚshowzImageWindow.show[   s¤   € ð  Œ;�"œ(Ò"Ð"ÝðM¨E¬Kð Mð Mð Mñô ð õ & eÑ,Ô,ˆŒØ×ÒÑÔÐØ×ÒÑÔÐØŒ
×#Ò#Ñ%Ô%Ð%ØŒ
×ÒÑÔÐÐÐr'   r   Údelay_msÚintú
str | Nonec                ó  — | j         €	| j        sdS |                      ¦   «          | j        r| j                             d¦  «        S | j         }|dk    r|                      ¦   «          nw|                     || j        ¦  «        }|                      ¦   «          | j         �At          t          ¦  «        5  | 	                    |¦  «         ddd¦  «         n# 1 swxY w Y   | j        r| j                             d¦  «        ndS )aÀ  Wait for a keypress and return its name.

        Args:
            delay_ms: How long to wait in milliseconds. ``0`` blocks until a
                key is pressed. Positive values poll for up to `delay_ms` ms
                and return ``None`` if no key arrives in time.

        Returns:
            The tkinter keysym string (e.g. ``"q"``, ``"Return"``, ``"Escape"``)
            or ``None`` if the timeout elapsed without a key event.
        Nr   )
r   r   r0   ÚpopÚ_wait_for_key_or_closeÚafterÚ_signal_waitr   Ú	ExceptionÚafter_cancel)r$   r5   ÚrootÚ
timeout_ids       r%   Úwait_keyzImageWindow.wait_keyv   s8  € ð Œ:Ð d¤oÐØ�4Ø×ÒÑÔÐØŒ?ð 	*Ø”?×&Ò& qÑ)Ô)Ð)ØŒzˆØ�qŠ=ˆ=Ø×'Ò'Ñ)Ô)Ð)Ð)àŸš H¨dÔ.?Ñ@Ô@ˆJØ×'Ò'Ñ)Ô)Ð)ØŒzÐ%Ý�iÑ(Ô(ð 2ð 2Ø×%Ò% jÑ1Ô1Ð1ð2ð 2ð 2ñ 2ô 2ð 2ð 2ð 2ð 2ð 2ð 2øøøð 2ð 2ð 2ð 2à)-¬ÐBˆtŒ×"Ò" 1Ñ%Ô%Ð%¸dÐBs   Â2CÃCÃCÚcallbackúMouseCallback | Nonec                ó   — || _         dS )a  Register a callback for mouse events on the image.

        Args:
            callback: Callable receiving ``(x, y, event_type)`` where
                ``event_type`` is one of ``"down"``, ``"up"``, or ``"move"``.
                Pass ``None`` to remove the callback.
        N)r   )r$   rB   s     r%   Úset_mouse_callbackzImageWindow.set_mouse_callback’   s   € ð  (ˆÔÐÐr'   c                ó*   — |                       ¦   «         S )z9Return whether the underlying Tk window currently exists.)Ú_window_exists©r$   s    r%   Úis_openzImageWindow.is_openœ   s   € ð ×"Ò"Ñ$Ô$Ð$r'   c                óö   — | j         �q| j         }|                      ¦   «          t          t          ¦  «        5  |                     ¦   «          ddd¦  «         n# 1 swxY w Y   |                      ¦   «          dS dS )z-Destroy the window and release its resources.N)r   r<   r   r=   ÚdestroyÚ_reset_window_refs)r$   r?   s     r%   ÚclosezImageWindow.close¡   s³   € àŒ:Ð!Ø”:ˆDØ×ÒÑÔÐÝ�)Ñ$Ô$ð ð Ø—’‘”�ðð ð ñ ô ð ð ð ð ð ð øøøð ð ð ð à×#Ò#Ñ%Ô%Ð%Ð%Ð%ð "Ð!s   ·AÁAÁAc                ó   — | S ©N© rH   s    r%   Ú	__enter__zImageWindow.__enter__ª   s   € Øˆr'   Ú_Úobjectc                ó.   — |                       ¦   «          d S rO   )rM   )r$   rR   s     r%   Ú__exit__zImageWindow.__exit__­   s   € Ø�
Š
‰Œˆˆˆr'   c                ó   ‡ — ‰                       ¦   «         rd S ‰                      ¦   «          dd l}|                     ¦   «         ‰ _        ‰ j                             ‰ j        ¦  «         |                     ‰ j        ¦  «        ‰ _        ‰ j                             dd¬¦  «         | 	                    ‰ j        d¬¦  «        ‰ _
        ‰ j                             d‰ j        ¦  «         ‰ j                             d‰ j        ¦  «         ‰ j                             d‰ j        ¦  «         ‰ j                             d	ˆ fd
„¦  «         ‰ j                             dˆ fd„¦  «         ‰ j                             dˆ fd„¦  «         d S )Nr   TÚboth)ÚexpandÚfill)ÚmasterÚvaluez<Key>z<Configure>ÚWM_DELETE_WINDOWz
<Button-1>c                ó0   •— ‰                      | d¦  «        S )NÚdown©Ú	_on_mouse©Úer$   s    €r%   ú<lambda>z,ImageWindow._ensure_window.<locals>.<lambda>¾   s   ø€ °·²ÀÀ6Ñ1JÔ1J€ r'   z<ButtonRelease-1>c                ó0   •— ‰                      | d¦  «        S )NÚupr_   ra   s    €r%   rc   z,ImageWindow._ensure_window.<locals>.<lambda>¿   s   ø€ ¸¿ºÀqÈ$Ñ8OÔ8O€ r'   z<Motion>c                ó0   •— ‰                      | d¦  «        S )NÚmover_   ra   s    €r%   rc   z,ImageWindow._ensure_window.<locals>.<lambda>À   s   ø€ ¨t¯~ª~¸aÀÑ/HÔ/H€ r'   )rG   rL   ÚtkinterÚTkr   r   ÚLabelr   ÚpackÚIntVarr   ÚbindÚ_on_keyÚ_on_configureÚprotocolrM   )r$   Útks   ` r%   r0   zImageWindow._ensure_window°   sc  ø€ Ø×ÒÑ Ô ð 	ØˆFØ×ÒÑ!Ô!Ð!ØÐÐÐà—U’U‘W”WˆŒ
ØŒ
×Ò˜œÑ$Ô$Ð$Ø—h’h˜tœzÑ*Ô*ˆŒØŒ×Ò ¨6ÐÑ2Ô2Ð2ØŸ)š)¨4¬:¸Q˜)Ñ?Ô?ˆŒØŒ
�Š˜ ¤Ñ.Ô.Ð.ØŒ
�Š˜ tÔ'9Ñ:Ô:Ð:ØŒ
×ÒÐ.°´
Ñ;Ô;Ð;ØŒ×Ò˜Ð'JÐ'JÐ'JÐ'JÑKÔKÐKØŒ×ÒÐ,Ð.OÐ.OÐ.OÐ.OÑPÔPÐPØŒ×Ò˜Ð%HÐ%HÐ%HÐ%HÑIÔIÐIÐIÐIr'   Úeventr   c                óæ   — |j         | j        urd S |j        |j        }}|dk    rF|dk    rB||f| j        | j        fk    r0||c| _        | _        | j        �|                      ¦   «          d S d S d S d S d S ©Né   )Úwidgetr   ÚwidthÚheightr   r   r   r1   )r$   rr   ÚwÚhs       r%   ro   zImageWindow._on_configureÂ   s’   € ØŒ<˜tœzÐ)Ð)ØˆFØŒ{˜EœLˆ1ˆØˆqŠ5ˆ5�Q˜’U�U  1˜v¨$¬+°t´{Ð)CÒCÐCØ'(¨!Ð$ˆDŒK˜œØŒÐ*Ø×$Ò$Ñ&Ô&Ð&Ð&Ð&ð ˆ5�U�UÐCÐCà*Ð*r'   c                óL  — | j         �| j        €d S ddlm} | j         }| j        dk    r,| j        dk    r!t          || j        | j        | j        ¦  «        }|                      |¦  «         | 	                    |¦  «        | _
        | j                             | j
        ¬¦  «         d S )Nr   )ÚImageTkru   ©r(   )r   r   ÚPILr|   r   r   Ú
_fit_imager   Ú_update_display_transformÚ
PhotoImager   Ú	configure)r$   r|   Úimgs      r%   r1   zImageWindow._update_displayË   s¨   € ØŒ?Ð" d¤kÐ&9ØˆFØÐÐÐÐÐàŒoˆØŒ;˜Š?ˆ?˜tœ{¨Qš˜Ý˜S $¤+¨t¬{¸DÔ<RÑSÔSˆCØ×&Ò& sÑ+Ô+Ð+Ø×(Ò(¨Ñ-Ô-ˆŒØŒ×Ò D¤KÐÑ0Ô0Ð0Ð0Ð0r'   ÚfittedúImage.Imagec                ó>  — | j         €dS | j         j        \  }}|j        \  }}| j        dk    r| j        n|}| j        dk    r| j        n|}|r||z  nd| _        |r||z  nd| _        t          d||z
  dz  ¦  «        | _        t          d||z
  dz  ¦  «        | _        dS )a¶  Record the scale and letterbox offset from the last display pass.

        The fitted image is drawn centered inside the label, so mouse events on
        the label carry display-space coordinates. Storing the per-axis scale
        and centering offset lets `_on_mouse` invert the transform back to
        original image-pixel coordinates. Falls back to an identity transform
        while the window geometry is still unknown.
        Nru   r   r   é   )	r   Úsizer   r   r    r!   Úmaxr"   r#   )r$   r„   Úorig_wÚorig_hÚfit_wÚfit_hÚwin_wÚwin_hs           r%   r€   z%ImageWindow._update_display_transform×   sº   € ð Œ?Ð"ØˆFØœÔ-‰ˆ�Ø”{‰ˆˆuØ#œ{¨Qš˜�”�°EˆØ#œ{¨Qš˜�”�°EˆØ28Ð A ¨¡ ¸cˆÔØ28Ð A ¨¡ ¸cˆÔÝ!$ S¨5°5©=¸AÑ*=Ñ!>Ô!>ˆÔÝ!$ S¨5°5©=¸AÑ*=Ñ!>Ô!>ˆÔÐÐr'   c                ól   — | j                              |j        ¦  «         |                      ¦   «          d S rO   )r   ÚappendÚkeysymr<   )r$   rr   s     r%   rn   zImageWindow._on_keyë   s2   € ØŒ×Ò˜uœ|Ñ,Ô,Ð,Ø×ÒÑÔÐÐÐr'   Ú
event_typec                óŒ   — | j         €d S |                      |j        |j        ¦  «        \  }}|                       |||¦  «         d S rO   )r   Ú_to_image_coordsÚxÚy)r$   rr   r“   r–   r—   s        r%   r`   zImageWindow._on_mouseï   sK   € ØÔÐ'ØˆFØ×$Ò$ U¤W¨e¬gÑ6Ô6‰ˆˆ1Ø×Ò˜Q  :Ñ.Ô.Ð.Ð.Ð.r'   Úevent_xÚevent_yútuple[int, int]c                ó>  — | j         €||fS | j         j        \  }}t          || j        z
  | j        z  ¦  «        }t          || j        z
  | j        z  ¦  «        }t          t          |d¦  «        |dz
  ¦  «        }t          t          |d¦  «        |dz
  ¦  «        }||fS )aÃ  Map label-space event coordinates to original image pixels.

        Inverts the scale and letterbox offset recorded by `_update_display`
        so callbacks receive coordinates in the source image's pixel space,
        regardless of how the window has been resized. Results are rounded to
        the nearest pixel and clamped inside the image bounds. When no image
        has been shown, the raw event coordinates are returned unchanged.
        Nr   ru   )	r   rˆ   Úroundr"   r    r#   r!   Úminr‰   )	r$   r˜   r™   rŠ   r‹   Úimage_xÚimage_yÚ	clamped_xÚ	clamped_ys	            r%   r•   zImageWindow._to_image_coordsõ   s    € ð Œ?Ð"Ø˜GÐ#Ð#ØœÔ-‰ˆ�Ý˜ 4Ô#9Ñ9¸TÔ=RÑRÑSÔSˆÝ˜ 4Ô#9Ñ9¸TÔ=RÑRÑSÔSˆÝ�˜G Q™œ¨°!©Ñ4Ô4ˆ	Ý�˜G Q™œ¨°!©Ñ4Ô4ˆ	Ø˜)Ð#Ð#r'   c                óÚ   — | j         €d S t          t          ¦  «        5  | j                              | j                              ¦   «         dz   ¦  «         d d d ¦  «         d S # 1 swxY w Y   d S rt   )r   r   r=   ÚsetÚgetrH   s    r%   r<   zImageWindow._signal_wait  sª   € ØŒ?Ð"ØˆFÝ•iÑ Ô ð 	;ð 	;ØŒO×Ò ¤× 3Ò 3Ñ 5Ô 5¸Ñ 9Ñ:Ô:Ð:ð	;ð 	;ð 	;ñ 	;ô 	;ð 	;ð 	;ð 	;ð 	;ð 	;ð 	;ð 	;øøøð 	;ð 	;ð 	;ð 	;ð 	;ð 	;s   ž5A Á A$Á'A$c                óÂ   — | j         �| j        €d S | j        rd S 	 | j                              | j        ¦  «         d S # t          $ r |                      ¦   «          Y d S w xY wrO   )r   r   r   Úwait_variabler=   rL   rH   s    r%   r:   z"ImageWindow._wait_for_key_or_close  s~   € ØŒ:Ð ¤Ð!8ØˆFØŒ?ð 	ØˆFð	&ØŒJ×$Ò$ T¤_Ñ5Ô5Ð5Ð5Ð5øÝð 	&ð 	&ð 	&Ø×#Ò#Ñ%Ô%Ð%Ð%Ð%Ð%ð	&øøøs   ›< ¼AÁAc                ó„   — | j         €dS 	 t          | j                              ¦   «         ¦  «        S # t          $ r Y dS w xY w)NF)r   r   Úwinfo_existsr=   rH   s    r%   rG   zImageWindow._window_exists  sR   € ØŒ:ÐØ�5ð	Ý˜œ
×/Ò/Ñ1Ô1Ñ2Ô2Ð2øÝð 	ð 	ð 	Ø�5�5ð	øøøs   ‹%1 ±
?¾?c                óÒ   — d | _         d | _        d | _        d | _        | j                             ¦   «          d| _        d| _        d| _        d| _	        d| _
        d| _        d | _        d S r   )r   r   r   r   r   Úclearr   r   r    r!   r"   r#   r   rH   s    r%   rL   zImageWindow._reset_window_refs  sk   € ØˆŒ
ØˆŒØˆŒØˆŒØŒ×ÒÑÔÐØˆŒØˆŒØ #ˆÔØ #ˆÔØ!$ˆÔØ!$ˆÔØˆŒˆˆr'   N)r   T)r   r   r   r   r   r   )r(   r)   r   r   )r   )r5   r6   r   r7   )rB   rC   r   r   )r   r   )r   r   )r   r   )rR   rS   r   r   )rr   r   r   r   )r„   r…   r   r   )rr   r   r“   r   r   r   )r˜   r6   r™   r6   r   rš   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r&   r4   rA   rE   ÚpropertyrI   rM   rQ   rU   r0   ro   r1   r€   rn   r`   r•   r<   r:   rG   rL   rP   r'   r%   r   r      sÁ  € € € € € ð5ð 5ðp EIð,ð ,ð ,ð ,ð ,ð&ð ð ð ð6Cð Cð Cð Cð Cð8(ð (ð (ð (ð ð%ð %ð %ñ „Xð%ð&ð &ð &ð &ðð ð ð ðð ð ð ðJð Jð Jð Jð$'ð 'ð 'ð 'ð
1ð 
1ð 
1ð 
1ð?ð ?ð ?ð ?ð(ð ð ð ð/ð /ð /ð /ð$ð $ð $ð $ð$;ð ;ð ;ð ;ð&ð &ð &ð &ðð ð ð ðð ð ð ð ð r'   r   Tr(   r…   rw   r6   rx   r   r   r   c                ó6  — | j         \  }}|rWt          ||z  ||z  ¦  «        }t          dt          ||z  ¦  «        ¦  «        t          dt          ||z  ¦  «        ¦  «        }}n||}}||f||fk    r| S |                      ||ft
          j        j        ¦  «        S rt   )rˆ   r�   r‰   rœ   Úresizer   Ú
ResamplingÚLANCZOS)	r(   rw   rx   r   ÚiwÚihÚscaleÚnew_wÚnew_hs	            r%   r   r   .  s¤   € ð ŒZ�F€BˆØð %Ý�E˜B‘J ¨¡Ñ,Ô,ˆÝ˜1�e B¨¡JÑ/Ô/Ñ0Ô0µ#°a½¸rÀE¹zÑ9JÔ9JÑ2KÔ2Kˆuˆˆà˜fˆuˆØˆu€~˜"˜b˜Ò!Ð!ØˆØ�<Š<˜ ˜­Ô(8Ô(@ÑAÔAÐAr'   r)   c                ó    — t          | ¦  «        S )züConvert a BGR, grayscale, or BGRA OpenCV array to a Pillow image.

    Thin wrapper delegating to `sv.cv2_to_pillow`, which reorders channels
    from OpenCV's BGR(A) convention to Pillow's RGB(A) and passes grayscale
    arrays through unchanged.
    r   r}   s    r%   r/   r/   <  s   € õ ˜ÑÔÐr'   )T)
r(   r…   rw   r6   rx   r6   r   r   r   r…   )r(   r)   r   r…   )Ú
__future__r   Úcollections.abcr   Ú
contextlibr   Útypingr   Únumpyr,   Únumpy.typingÚnptr~   r   Úsupervision.utils.conversionr	   r6   r   ÚMouseCallbackr   r   r/   rP   r'   r%   ú<module>rÃ      s  ðØ "Ð "Ð "Ð "Ð "Ð "à $Ð $Ð $Ð $Ð $Ð $Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð à Ð Ð Ð Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð à 6Ð 6Ð 6Ð 6Ð 6Ð 6à˜#˜s C˜¨$Ð.Ô/€ð[ð [ð [ð [ð [ñ [ô [ð [ð~ LPðBð Bð Bð Bð Bð ð  ð  ð  ð  ð  r'   