§
    ­¸jM%  ã                  ó´   — d Z ddlmZ ddlZddlZddlmZ ddlmZ ddl	Z
ddlmZ 	 ddlZn# e$ r dZY nw xY wddlmZ dZdd„Zdd„Zdd„Zdd d„Zdd!d„ZdS )"zSImage decoding shared by the dataset readers, independent of any annotation format.é    )ÚannotationsN)ÚPath)ÚIO)ÚNDArray)ÚImages   ÿØÚwidthÚintÚheightÚ
draft_sizeú
int | NoneÚreturnc                óp   ‡— |€dS t          | |z  ||z  ¦  «        Št          ˆfd„dD ¦   «         d¦  «        S )aa  Return the power-of-two factor ``PIL.Image.draft`` would reduce a JPEG by for a square ``draft_size`` box.

    Mirrors ``JpegImageFile.draft``: the largest of 8, 4, 2 that keeps both axes at or above ``draft_size``, else 1.
    Pinning this factor explicitly matters because libjpeg-turbo can also scale by 3/8, 5/8, ... and would otherwise
    pick a finer, slower reduction than Pillow for the same box.

    Examples:
        >>> _jpeg_draft_reduction(2000, 2000, 700)
        2
        >>> _jpeg_draft_reduction(2000, 2000, None)
        1
        >>> _jpeg_draft_reduction(513, 1024, 512)
        1
    Né   c              3  ó(   •K  — | ]}‰|k    ¯|V — Œd S ©N© )Ú.0ÚfactorÚscales     €úh/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/datasets/io_utils.pyú	<genexpr>z(_jpeg_draft_reduction.<locals>.<genexpr>-   s'   øè è € ÐCÐC˜F°5¸F²?°?�°?°?°?°?ÐCÐCó    )é   é   é   )ÚminÚnext)r   r
   r   r   s      @r   Ú_jpeg_draft_reductionr      sN   ø€ ð ÐØˆqÝ�˜Ñ# V¨zÑ%9Ñ:Ô:€EÝÐCÐCÐCÐC iÐCÑCÔCÀQÑGÔGÐGr   ÚNonec                ó  — t           j        }|€dS t          d| ¦  «        t          d|¦  «        z  }|d|z  k    r d|› dd|z  › d�}t          j        |¦  «        ‚||k    r(t	          j        d|› d|› d�t           j        ¦  «         dS dS )a:  Apply Pillow's decompression-bomb guard to a header size before any pixel buffer is allocated.

    Mirrors ``PIL.Image._decompression_bomb_check`` through public names only.  ``PIL.Image.MAX_IMAGE_PIXELS`` is
    read at call time, so a process-wide override (``rfdetr.datasets.o365`` raises it) still applies and ``None``
    disables the guard; more than twice the limit raises and more than the limit warns, with Pillow's own wording so
    callers filtering on the message see the same text from either decoder.

    Args:
        width: Full-size image width from the header.
        height: Full-size image height from the header.

    Raises:
        PIL.Image.DecompressionBombError: If ``width * height`` exceeds twice ``PIL.Image.MAX_IMAGE_PIXELS``.

    Examples:
        >>> _check_decompression_bomb(10, 10)
    Nr   r   zImage size (z pixels) exceeds limit of z0 pixels, could be decompression bomb DOS attack.)r   ÚMAX_IMAGE_PIXELSÚmaxÚDecompressionBombErrorÚwarningsÚwarnÚDecompressionBombWarning)r   r
   ÚlimitÚpixelsÚmsgs        r   Ú_check_decompression_bombr*   0   s»   € õ$ Ô"€EØ€}Øˆå��E‰]Œ]�S  F™^œ^Ñ+€Fà��E‘	ÒÐàx˜6ÐxÐx¸QÀ¹YÐxÐxÐxð 	õ Ô*¨3Ñ/Ô/Ð/à�‚~€~ÝŒØt˜6ÐtÐt¸UÐtÐtÐtÝÔ*ñ	
ô 	
ð 	
ð 	
ð 	
ð €~r   ÚsourceúPath | IO[bytes]ú-tuple[NDArray[np.uint8], tuple[float, float]]c                ó4  — t          j        | ¦  «        5 }|j        \  }}|�|                     d||f¦  «         t	          j        |                     d¦  «        ¦  «        }ddd¦  «         n# 1 swxY w Y   ||j        d         |z  |j        d         |z  ffS )a  Decode a file or an in-memory stream through Pillow into a writeable RGB array with its decode scales.

    The fallback both entry points share: ``PIL.Image.draft`` applies the JPEG reduction when ``draft_size`` is set
    (a no-op for other formats) and ``np.array`` copies the converted pixels into a buffer that outlives the closed
    image.

    Args:
        source: Image file path, or a binary stream positioned at the start of the encoded bytes.
        draft_size: Smallest extent the caller can consume without upscaling, or ``None`` for full resolution.

    Returns:
        Decoded ``(H, W, 3)`` uint8 RGB pixels and their horizontal/vertical decode scales, both ``1.0`` when the
        decoder did not reduce.

    Examples:
        >>> encoded = io.BytesIO()
        >>> Image.fromarray(np.zeros((32, 64, 3), dtype=np.uint8)).save(encoded, format="JPEG")
        >>> pixels, scales = _decode_with_pillow(io.BytesIO(encoded.getvalue()), draft_size=16)
        >>> pixels.shape, scales
        ((16, 32, 3), (0.5, 0.5))
    NÚRGBr   r   )r   ÚopenÚsizeÚdraftÚnpÚarrayÚconvertÚshape)r+   r   ÚimageÚ
full_widthÚfull_heightr(   s         r   Ú_decode_with_pillowr:   U   sÔ   € õ0 
Œ�FÑ	Ô	ð 0˜uØ"'¤*Ñˆ
�KØÐ!Ø�KŠK˜ 
¨JÐ7Ñ8Ô8Ð8Ý”˜%Ÿ-š-¨Ñ.Ô.Ñ/Ô/ˆð	0ð 0ð 0ñ 0ô 0ð 0ð 0ð 0ð 0ð 0ð 0øøøð 0ð 0ð 0ð 0ð
 �F”L ”O jÑ0°&´,¸q´/ÀKÑ2OÐPÐPÐPs   •AA-Á-A1Á4A1Úpathr   c                ór  — t           �¡|                      d¦  «        5 }|                     t          t          ¦  «        ¦  «        t          k    rC|                     d¦  «         t          |                     ¦   «         |¦  «        cddd¦  «         S 	 ddd¦  «         n# 1 swxY w Y   t          | |¦  «        S )a;
  Decode an image file to RGB, optionally downscaling during the JPEG discrete cosine transform (DCT) decode.

    JPEG files go through ``simplejpeg`` (libjpeg-turbo straight into a NumPy buffer) when it is installed.  Its
    output matches Pillow's to within decoder rounding: both wrap libjpeg-turbo, but the two packages can bundle
    different builds, which can introduce small rounding differences.  Everything else falls back to Pillow and
    copies its image into an array: non-JPEG files, a missing ``simplejpeg``, and any JPEG it rejects, so error
    behavior does not depend on the optional package either.  That includes Pillow's decompression-bomb guard
    (``PIL.Image.MAX_IMAGE_PIXELS``), which the ``simplejpeg`` path applies to the full-size header dimensions
    before allocating, exactly as ``PIL.Image.open`` would.

    Returning an array rather than a PIL image lets a caller that wants an array skip a round trip, which is where the
    speedup lands: 1.3-1.8x over Pillow at the decode stage for array consumers such as ``_LazyYoloDetectionDataset``,
    varying with image size and with how much high-frequency detail the JPEG carries.  Most of that array-out gain comes
    from skipping Pillow's ``convert("RGB")`` and ``np.array`` copies rather than from a faster codec: the raw
    libjpeg-turbo decode itself is only about 12% faster, since Pillow's wheels link the same library.  Callers needing
    a PIL image wrap the result with ``Image.fromarray`` (``YoloDetection``, ``CocoDetection``, the WebDataset reader);
    that wrap costs about what the faster decode saves, so the net effect there is hardware-dependent: ``YoloDetection``
    keeps a smaller end-to-end gain because its previous path copied through ``np.array`` too, while other PIL-out
    consumers may see a slight regression on some platforms until the CPU pipeline consumes arrays directly, and take
    the shared decoder policy rather than a speedup.

    When ``draft_size`` is set, both decoders apply the same power-of-two reduction ``PIL.Image.draft`` would choose to
    keep the image at least ``draft_size`` on both axes; it is a no-op for non-JPEG files.

    Args:
        path: Image file to decode.
        draft_size: Smallest extent the caller can consume without upscaling, or ``None`` for full resolution.

    Returns:
        Decoded ``(H, W, 3)`` uint8 RGB pixels and their horizontal/vertical decode scales, both ``1.0`` when the
        decoder did not reduce.

    Raises:
        PIL.Image.DecompressionBombError: If the image has more than twice ``PIL.Image.MAX_IMAGE_PIXELS`` pixels.
    NÚrbr   )Ú
simplejpegr0   ÚreadÚlenÚ	_JPEG_SOIÚseekÚdecode_image_bytesr:   )r;   r   Úencodeds      r   Údecode_imagerE   u   s  € õH ÐØ�YŠY�t‰_Œ_ð 	F Ø�|Š|�C¥	™NœNÑ+Ô+­yÒ8Ð8Ø—’˜Q‘”�Ý)¨'¯,ª,©.¬.¸*ÑEÔEð	Fð 	Fð 	Fð 	Fñ 	Fô 	Fð 	Fð 	FØ8ð	Fð 	Fð 	Fñ 	Fô 	Fð 	Fð 	Fð 	Fð 	Fð 	Fð 	Føøøð 	Fð 	Fð 	Fð 	Fõ
 ˜t ZÑ0Ô0Ð0s   �A'BÂB"Â%B"ÚdataÚbytesc                óð  — t           �Î|                      t          ¦  «        r´	 t          j        | ¦  «        }t	          |d         ¦  «        t	          |d         ¦  «        }}t          ||¦  «         t          |||¦  «        }t          j        | d| |z   | |z   ¬¦  «        }||j        d         |z  |j        d         |z  ffS # t          $ r Y nw xY wt          t          j        | ¦  «        |¦  «        S )a  Decode encoded image bytes to RGB, optionally downscaling during the JPEG DCT (discrete cosine transform) decode.

    Holds the decoder policy :func:`decode_image` applies; readers that already have the encoded bytes in memory, such
    as the WebDataset loader reading a shard member, call this directly instead of writing the file out first.

    Args:
        data: Encoded image bytes.
        draft_size: Smallest extent the caller can consume without upscaling, or ``None`` for full resolution.

    Returns:
        Decoded ``(H, W, 3)`` uint8 RGB pixels and their horizontal/vertical decode scales, both ``1.0`` when the
        decoder did not reduce.

    Raises:
        PIL.Image.DecompressionBombError: If the image has more than twice ``PIL.Image.MAX_IMAGE_PIXELS`` pixels.
    Nr   r   r/   )Ú
colorspaceÚ
min_heightÚ	min_width)r>   Ú
startswithrA   Údecode_jpeg_headerr	   r*   r   Údecode_jpegr6   Ú
ValueErrorr:   ÚioÚBytesIO)rF   r   Úheaderr9   r8   Ú	reductionr(   s          r   rC   rC   ¢   s  € õ" Ð $§/¢/µ)Ñ"<Ô"<Ðð	YÝÔ2°4Ñ8Ô8ˆFÝ&)¨&°¬)¡n¤nµc¸&À¼)±n´n˜ˆKå% j°+Ñ>Ô>Ð>Ý-¨j¸+ÀzÑRÔRˆIÝÔ+ØØ Ø)˜\¨YÑ6Ð7Ø'˜K¨9Ñ4Ð5ð	ñ ô ˆFð ˜FœL¨œO¨jÑ8¸&¼,Àq¼/ÈKÑ:WÐXÐXÐXøõ ð 	ð 	ð 	ØˆDð	øøøõ �rœz¨$Ñ/Ô/°Ñ<Ô<Ð<s   £BC Ã
CÃC)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   rG   r   r   r   r-   )Ú__doc__Ú
__future__r   rP   r$   Úpathlibr   Útypingr   Únumpyr3   Únumpy.typingr   r>   ÚImportErrorÚPILr   rA   r   r*   r:   rE   rC   r   r   r   ú<module>r\      sF  ðð ZÐ Yà "Ð "Ð "Ð "Ð "Ð "à 	€	€	€	Ø €€€Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð à Ð Ð Ð Ø  Ð  Ð  Ð  Ð  Ð  ðØÐÐÐÐøØð ð ð Ø€J€J€Jðøøøà Ð Ð Ð Ð Ð à€	ðHð Hð Hð Hð*"
ð "
ð "
ð "
ðJQð Qð Qð Qð@*1ð *1ð *1ð *1ð *1ðZ"=ð "=ð "=ð "=ð "=ð "=ð "=s   ¨- ­7¶7