o
    h]                  
   @  s  d 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 dd	lmZ dd
lmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ zddl Z W n e!yt Z" zddl#m$Z$ e$e"Z W Y dZ"["ndZ"["ww G dd dZ%G dd de%Z&G dd de%Z'G dd de%Z(G dd dZ)d2ddZ*d3d4ddZ+d3d4dd Z,d5d&d'Z-d6d*d+Z.d7d.d/Z/d8d0d1Z0dS )9z8Functions and classes for heif images to read and write.    )annotations)copydeepcopy)SEEK_SET)Any)Image   )options)HeifCompressionFormat)	MODE_INFO	CtxEncode	MimCImage_exif_from_pillow
_get_bytes_get_heif_meta_get_orientation_for_encoder_get_primary_index_pil_to_supported_mode_retrieve_exif_retrieve_xmp_rotate_pil_xmp_from_pillowget_file_mimetypesave_colorspace_chromaset_orientationN)DeferredErrorc                   @  sh   e Zd ZU dZded< 	 ded< 	 dd Zedd	 ZedddZedd Z	dddZ
dddZdS )	BaseImagez^Base class for :py:class:`HeifImage`, :py:class:`HeifDepthImage` and :py:class:`HeifAuxImage`.tuple[int, int]sizestrmodec                 C  s   |j \| _| _|| _d | _d S N)	size_moder   r    _c_image_data)selfc_image r'   P/var/www/html/ndineBlogger/venv/lib/python3.10/site-packages/pillow_heif/heif.py__init__4   s   
zBaseImage.__init__c                 C  s   |    | jS )zaDecodes image and returns image data.

        :returns: ``bytes`` of the decoded image.
        )loadr$   r%   r'   r'   r(   data9   s   zBaseImage.datareturnintc                 C  s   |    | jjS )zStride of the image.

        .. note:: from `0.10.0` version this value always will have width * sizeof pixel in default usage mode.

        :returns: An Int value indicating the image stride after decoding.
        )r*   r#   strider+   r'   r'   r(   r/   B   s   zBaseImage.stridec                 C  s   |    t| jt| j d  }t| j d dkrd}nt|d }d}| jd |f}t| j d dkr>|t| j d f7 }||d| jdS )	zNumpy array interface support.r   r      z|u1   z<u2   )shapetypestrversionr,   )r*   r.   r/   r   r    r   r,   )r%   widthr4   r3   r'   r'   r(   __array_interface__M   s   zBaseImage.__array_interface__Image.Imagec                 C  s&   |    t| j| j| jd| j| jS )Helper method to create :external:py:class:`~PIL.Image.Image` class.

        :returns: :external:py:class:`~PIL.Image.Image` class created from an image.
        raw)r*   r   	frombytesr    r   r,   r/   r+   r'   r'   r(   	to_pillow\   s   zBaseImage.to_pillowNonec                 C  s&   | j s| jj| _ | jj\| _}dS dS )zMethod to decode image.

        .. note:: In normal cases, you should not call this method directly,
            when reading `data` or `stride` property of image will be loaded automatically.
        N)r$   r#   r,   r"   r   )r%   _r'   r'   r(   r*   k   s   
zBaseImage.loadN)r-   r.   r-   r8   r-   r=   )__name__
__module____qualname____doc____annotations__r)   propertyr,   r/   r7   r<   r*   r'   r'   r'   r(   r   (   s   
 



r   c                      s6   e Zd ZdZ fddZdd Zd
 fdd	Z  ZS )HeifDepthImagez`Class representing the depth image associated with the :py:class:`~pillow_heif.HeifImage` class.c                   s,   t  | |j}d|i| _t|| j d S )Nmetadata)superr)   rH   infor   )r%   r&   rH   	__class__r'   r(   r)   y   s
   zHeifDepthImage.__init__c              	   C  0   d| j j d| jd  d| jd  d| j d	S N< r   xr   >rL   rA   r   r    r+   r'   r'   r(   __repr__      0zHeifDepthImage.__repr__r-   r8   c                   s   t   }| j |_|S )r9   )rI   r<   rJ   r   r%   imagerK   r'   r(   r<      s   
zHeifDepthImage.to_pillowr?   )rA   rB   rC   rD   r)   rT   r<   __classcell__r'   r'   rK   r(   rG   v   s
    rG   c                   @  s   e Zd ZdZdd ZdS )HeifAuxImagezdClass representing the auxiliary image associated with the :py:class:`~pillow_heif.HeifImage` class.c              	   C  rM   rN   rS   r+   r'   r'   r(   rT      rU   zHeifAuxImage.__repr__N)rA   rB   rC   rD   rT   r'   r'   r'   r(   rY      s    rY   c                      sl   e Zd ZdZ fddZdd Zeddd	Zedd
dZej	dddZd fddZ
dddZ  ZS )	HeifImagez;One image in a :py:class:`~pillow_heif.HeifFile` container.c                   s:  t  | |j}t|}t|}tjrdd |jD ng }tjr)dd |j	D ng }t
|jt|j||||d| _tjr_i }|jD ]}||}	|	|vrRg ||	< ||	 | qC|| jd< t|}
|rj|| jd< |
rq|
| jd< t|| j |j}|r|d d	v r|d
 | jd< |d | jd< d S |d
 | jd< d S d S )Nc                 S  s   g | ]}|d ur|qS r!   r'   .0ir'   r'   r(   
<listcomp>   s    z&HeifImage.__init__.<locals>.<listcomp>c                 S     g | ]
}|d urt |qS r!   )rG   r[   r'   r'   r(   r^          )primary	bit_depthexifrH   
thumbnailsdepth_imagesauxxmpheiftype)rICCprofr,   icc_profileicc_profile_typenclx_profile)rI   r)   rH   r   r   r	   
THUMBNAILSrd   DEPTH_IMAGESdepth_image_listboolra   r.   rb   rJ   
AUX_IMAGESaux_image_idsget_aux_typeappendr   r   color_profile)r%   r&   rH   rc   rg   rd   re   ctx_aux_infoaux_idaux_type	heif_metarw   rK   r'   r(   r)      sF   




zHeifImage.__init__c                 C  sp   | j s	t| jtrt| j dnd}d| jj d| jd  d| jd  d| j	 d| d	t| j
d
g  dS )Nz bytesnorO   rP   r   rQ   r    with z image data and rd   z thumbnails>)r$   
isinstancer#   r   lenr,   rL   rA   r   r    rJ   get)r%   s_bytesr'   r'   r(   rT      s   &,zHeifImage.__repr__r-   rr   c                 C  s   | j jddd d dv S )zD``True`` for images with the ``alpha`` channel, ``False`` otherwise.;sepr   )Aa)r    splitr+   r'   r'   r(   	has_alpha   s   zHeifImage.has_alphac                 C  s   t | jjddd d dkS )zN``True`` for images with ``premultiplied alpha`` channel, ``False`` otherwise.r   r   r   r   r   )rr   r    r   r+   r'   r'   r(   premultiplied_alpha   s   zHeifImage.premultiplied_alphavaluec                 C  s.   | j r| j|r
dnd|rdnd| _d S d S )Nr   r   )r   r    replacer%   r   r'   r'   r(   r      s   $r8   c                   s*   t   }| j |_t|j|jd< |S )r9   original_orientation)rI   r<   rJ   r   r   rV   rK   r'   r(   r<      s   
zHeifImage.to_pillowry   r.   rY   c                 C  s   | j |}t|S )zMethod to retrieve the auxiliary image at the given ID.

        :returns: a :py:class:`~pillow_heif.HeifAuxImage` class instance.
        )r#   get_aux_imagerY   )r%   ry   	aux_imager'   r'   r(   r      s   zHeifImage.get_aux_imager-   rr   r   rr   r?   )ry   r.   r-   rY   )rA   rB   rC   rD   r)   rT   rF   r   r   setterr<   r   rX   r'   r'   rK   r(   rZ      s    '
rZ   c                   @  s  e Zd ZdZd?ddZedd Zed	d
 Zedd Zedd Z	e	j
d@ddZ	edd Zedd Zedd ZdAddZdBddZdd  Zd!d" Zd#d$ Zd%d& Zd'd( ZdCd-d.ZdDd1d2ZdEd3d4Zed5d6 Zd7d8 Zd9d: Zd;d< Zd=d> ZeZdS )FHeifFilea  Representation of the :py:class:`~pillow_heif.HeifImage` classes container.

    To create :py:class:`~pillow_heif.HeifFile` object, use the appropriate factory functions.

    * :py:func:`~pillow_heif.open_heif`
    * :py:func:`~pillow_heif.read_heif`
    * :py:func:`~pillow_heif.from_pillow`
    * :py:func:`~pillow_heif.from_bytes`

    Exceptions that can be raised when working with methods:
        `ValueError`, `EOFError`, `SyntaxError`, `RuntimeError`, `OSError`
    NTFc                 K  s  t |dr|dt |d u rg }d}nKt|}t|}|ddkr+tjdd}n|ddks9|ddkrAtjd	d}nd}t	
|tj|||d
d|dd|dtj|tj	}|| _dd |D | _d| _t| jD ]\}	}
|
jddr|	| _qrd S )Nseekr    avifr   AVIFheicrh   HEIFremove_strideThdr_to_16bitreload_sizec                 S  r_   r!   )rZ   r[   r'   r'   r(   r^     r`   z%HeifFile.__init__.<locals>.<listcomp>ra   F)hasattrr   r   r   r   findr	   PREFERRED_DECODERr   _pillow_heif	load_fileDECODE_THREADSALLOW_INCORRECT_HEADERSDISABLE_SECURITY_LIMITSmimetype_imagesprimary_index	enumeraterJ   )r%   fpconvert_hdr_to_8bitbgr_modekwargsimagesr   fp_bytespreferred_decoderindexr>   r'   r'   r(   r)      s>   


zHeifFile.__init__c                 C     | j | j jS )z:attr:`~pillow_heif.HeifImage.size` property of the primary :class:`~pillow_heif.HeifImage`.

        :exception IndexError: If there are no images.
        )r   r   r   r+   r'   r'   r(   r        zHeifFile.sizec                 C  r   )z:attr:`~pillow_heif.HeifImage.mode` property of the primary :class:`~pillow_heif.HeifImage`.

        :exception IndexError: If there are no images.
        )r   r   r    r+   r'   r'   r(   r       r   zHeifFile.modec                 C  r   )z:attr:`~pillow_heif.HeifImage.has_alpha` property of the primary :class:`~pillow_heif.HeifImage`.

        :exception IndexError: If there are no images.
        )r   r   r   r+   r'   r'   r(   r   (  r   zHeifFile.has_alphac                 C  r   )z:attr:`~pillow_heif.HeifImage.premultiplied_alpha` property of the primary :class:`~pillow_heif.HeifImage`.

        :exception IndexError: If there are no images.
        r   r   r   r+   r'   r'   r(   r   0  r   zHeifFile.premultiplied_alphar   rr   c                 C  s   || j | j _d S r!   r   r   r'   r'   r(   r   8  s   c                 C  r   )z:attr:`~pillow_heif.HeifImage.data` property of the primary :class:`~pillow_heif.HeifImage`.

        :exception IndexError: If there are no images.
        )r   r   r,   r+   r'   r'   r(   r,   <  r   zHeifFile.datac                 C  r   )z:attr:`~pillow_heif.HeifImage.stride` property of the primary :class:`~pillow_heif.HeifImage`.

        :exception IndexError: If there are no images.
        )r   r   r/   r+   r'   r'   r(   r/   D  r   zHeifFile.stridec                 C  r   )z`info`` dict of the primary :class:`~pillow_heif.HeifImage` in the container.

        :exception IndexError: If there are no images.
        )r   r   rJ   r+   r'   r'   r(   rJ   L  r   zHeifFile.infor-   r8   c                 C  s   | j | j  S )zHelper method to create Pillow :external:py:class:`~PIL.Image.Image`.

        :returns: :external:py:class:`~PIL.Image.Image` class created from the primary image.
        )r   r   r<   r+   r'   r'   r(   r<   T  s   zHeifFile.to_pillowr=   c                 K  s   t | j|fi | dS )a  Saves image(s) under the given fp.

        Keyword options can be used to provide additional instructions to the writer.
        If a writer does not recognize an option, it is silently ignored.

        Supported options:
            ``save_all`` - boolean. Should all images from ``HeiFile`` be saved?
            (default = ``True``)

            ``append_images`` - do the same as in Pillow. Accepts the list of ``HeifImage``

            .. note:: Appended images always will have ``info["primary"]=False``

            ``quality`` - see :py:attr:`~pillow_heif.options.QUALITY`

            ``enc_params`` - dictionary with key:value to pass to :ref:`x265 <hevc-encoder>` encoder.

            ``exif`` - override primary image's EXIF with specified.
            Accepts ``None``, ``bytes`` or ``PIL.Image.Exif`` class.

            ``xmp`` - override primary image's XMP with specified. Accepts ``None`` or ``bytes``.

            ``primary_index`` - ignore ``info["primary"]`` and set `PrimaryImage` by index.

            ``chroma`` - custom subsampling value. Possible values: ``444``, ``422`` or ``420`` (``x265`` default).

            ``subsampling`` - synonym for *chroma*. Format is string, compatible with Pillow: ``x:x:x``, e.g. '4:4:4'.

            ``format`` - string with encoder format name. Possible values: ``HEIF`` (default) or ``AVIF``.

            ``save_nclx_profile`` - boolean, see :py:attr:`~pillow_heif.options.SAVE_NCLX_PROFILE`

            ``matrix_coefficients`` - int, nclx profile: color conversion matrix coefficients, default=6 (see h.273)

            ``color_primaries`` - int, nclx profile: color primaries (see h.273)

            ``transfer_characteristic`` - int, nclx profile: transfer characteristics (see h.273)

            ``full_range_flag`` - nclx profile: full range flag, default: 1

        :param fp: A filename (string), pathlib.Path object or an object with `write` method.
        N)_encode_imagesr   )r%   r   r   r'   r'   r(   save[  s   +zHeifFile.savec                 C  s*   d| j j dt|  ddd | D  dS )NrO   r}   z	 images: c                 S  s   g | ]}t |qS r'   )r   r[   r'   r'   r(   r^     s    z%HeifFile.__repr__.<locals>.<listcomp>rR   )rL   rA   r   r+   r'   r'   r(   rT     s   *zHeifFile.__repr__c                 C  s
   t | jS r!   )r   r   r+   r'   r'   r(   __len__  s   
zHeifFile.__len__c                 c  s    | j E d H  d S r!   )r   r+   r'   r'   r(   __iter__  s   zHeifFile.__iter__c                 C  s.   |dk s|t | jkrtd| | j| S Nr   zinvalid image index: r   r   
IndexError)r%   r   r'   r'   r(   __getitem__  s   
zHeifFile.__getitem__c                 C  s0   |dk s|t | jkrtd| | j|= d S r   r   )r%   keyr'   r'   r(   __delitem__  s   zHeifFile.__delitem__r    r   r   r   c                 K  s(   t t|||fi |}| j| |S )aP  Adds image from bytes to container.

        .. note:: Supports ``stride`` value if needed.

        :param mode: see :ref:`image-modes`.
        :param size: tuple with ``width`` and ``height`` of image.
        :param data: bytes object with raw image data.

        :returns: :py:class:`~pillow_heif.HeifImage` added object.
        )rZ   r   r   rv   )r%   r    r   r,   r   added_imager'   r'   r(   add_frombytes  s   zHeifFile.add_frombytesrW   rZ   c                 C  s@   |   | j|j|j|j|jd}t|j|_|jdd |S )zAdd image to the container.

        :param image: :py:class:`~pillow_heif.HeifImage` class to add from.

        :returns: :py:class:`~pillow_heif.HeifImage` added object.
        )r/   ra   N)	r*   r   r    r   r,   r/   r   rJ   pop)r%   rW   r   r'   r'   r(   add_from_heif  s   zHeifFile.add_from_heifc           	      C  s
  |j d dks|j d dkrtd|j }t||d< t|}|r'||d< t|}t|}|dur<|dkr<t||}|	  | 
|j|j | }dD ]}||jv r\|j| |j|< qMdD ]}||jv rpt|j| |j|< q_t||jd< t|}|r||jd< |S )	zAdd image to the container.

        :param image: Pillow :external:py:class:`~PIL.Image.Image` class to add from.

        :returns: :py:class:`~pillow_heif.HeifImage` added object.
        r   r   zEmpty images are not supported.rc   rg   N)rb   rd   rl   rm   )rn   rH   )r   
ValueErrorrJ   r   r   r   r   r   r   r*   r   r    tobytesr   )	r%   rW   rJ   rg   r   imgr   r   im_xmpr'   r'   r(   add_from_pillow  s<   




zHeifFile.add_from_pillowc                 C  r   )z+Returns the primary image as a numpy array.)r   r   r7   r+   r'   r'   r(   r7     s   zHeifFile.__array_interface__c                 C  s@   g }| j D ]}t|j}||j|j||jg q| j| j|gS r!   )	r   bytesr,   rv   r    r   rJ   r   r   )r%   im_descimim_datar'   r'   r(   __getstate__  s
   

zHeifFile.__getstate__c           	      C  sD   |    |\| _| _}|D ]}|\}}}}| |||}||_qd S r!   )r)   r   r   r   rJ   )	r%   stater   r   im_modeim_sizer   im_infor   r'   r'   r(   __setstate__  s   zHeifFile.__setstate__c                 C  s&   t  }t| j|_| j|_| j|_|S r!   )r   r   r   r   r   )r%   im_copyr'   r'   r(   __copy  s
   zHeifFile.__copyc                 C  s   | j | j |S )z`get_aux_image`` method of the primary :class:`~pillow_heif.HeifImage` in the container.

        :exception IndexError: If there are no images.
        )r   r   r   )r%   ry   r'   r'   r(   r     s   zHeifFile.get_aux_image)NTFr   r?   r@   )r    r   r   r   )rW   rZ   r-   rZ   )rW   r8   r-   rZ   )rA   rB   rC   rD   r)   rF   r   r    r   r   r   r,   r/   rJ   r<   r   rT   r   r   r   r   r   r   r   r7   r   r   _HeifFile__copyr   __copy__r'   r'   r'   r(   r      sH    
"








-


$
r   r-   rr   c                 C  s*   t | d}|dd dkrdS t|dkS )aV  Checks if the given `fp` object contains a supported file type.

    :param fp: A filename (string), pathlib.Path object or a file object.
        The file object must implement ``file.read``, ``file.seek``, and ``file.tell`` methods,
        and be opened in binary mode.

    :returns: A boolean indicating if the object can be opened.
          r0   s   ftypFr   )r   r   )r   f_datar'   r'   r(   is_supported  s   
	r   TFc                 K  s   t | ||fi |S )a  Opens the given HEIF(AVIF) image file.

    :param fp: See parameter ``fp`` in :func:`is_supported`
    :param convert_hdr_to_8bit: Boolean indicating should 10 bit or 12 bit images
        be converted to 8-bit images during decoding. Otherwise, they will open in 16-bit mode.
        ``Does not affect "monochrome" or "depth images".``
    :param bgr_mode: Boolean indicating should be `RGB(A)` images be opened in `BGR(A)` mode.
    :param kwargs: **hdr_to_16bit** a boolean value indicating that 10/12-bit image data
        should be converted to 16-bit mode during decoding. `Has lower priority than convert_hdr_to_8bit`!
        Default = **True**

    :returns: :py:class:`~pillow_heif.HeifFile` object.
    :exception ValueError: invalid input data.
    :exception EOFError: corrupted image data.
    :exception SyntaxError: unsupported feature.
    :exception RuntimeError: some other error.
    :exception OSError: out of memory.
    )r   )r   r   r   r   r'   r'   r(   	open_heif  s   r   c                 K  s.   t | ||fddi|}|D ]}|  q|S )a\  Opens the given HEIF(AVIF) image file and decodes all images.

    .. note:: In most cases it is better to call :py:meth:`~pillow_heif.open_heif`, and
        let images decoded automatically only when needed.

    :param fp: See parameter ``fp`` in :func:`is_supported`
    :param convert_hdr_to_8bit: Boolean indicating should 10 bit or 12 bit images
        be converted to 8-bit images during decoding. Otherwise, they will open in 16-bit mode.
        ``Does not affect "monochrome" or "depth images".``
    :param bgr_mode: Boolean indicating should be `RGB(A)` images be opened in `BGR(A)` mode.
    :param kwargs: **hdr_to_16bit** a boolean value indicating that 10/12-bit image data
        should be converted to 16-bit mode during decoding. `Has lower priority than convert_hdr_to_8bit`!
        Default = **True**

    :returns: :py:class:`~pillow_heif.HeifFile` object.
    :exception ValueError: invalid input data.
    :exception EOFError: corrupted image data.
    :exception SyntaxError: unsupported feature.
    :exception RuntimeError: some other error.
    :exception OSError: out of memory.
    r   T)r   r*   )r   r   r   r   retr   r'   r'   r(   	read_heif*  s   
r   r    r   r   r   r=   c                 K  s,   t tt| ||fi |g|fi | dS )aR  Encodes data in a ``fp``.

    :param mode: `BGR(A);16`, `RGB(A);16`, LA;16`, `L;16`, `I;16L`, `BGR(A)`, `RGB(A)`, `LA`, `L`
    :param size: tuple with ``width`` and ``height`` of an image.
    :param data: bytes object with raw image data.
    :param fp: A filename (string), pathlib.Path object or an object with ``write`` method.
    N)r   rZ   r   )r    r   r,   r   r   r'   r'   r(   encodeF  s   ,r   r   list[HeifImage]c                 K  s$  | dd}|dkrtjntj}t | std| d| | dg  }| dds2|d d	 }|s8td
t|| d}t	|fi |}t
|D ]>\}}	|	  |	j }
d|
d< ||krm|
jdi | d|
d< |
dd |j|	j|	j|	jfdt|
i|
d|	ji qL|| d S )Nformatr   r   zNo z encoder found.append_imagessave_allTr   z)Cannot write file with no images as HEIF.r   Fra   r/   r   image_orientationr'   )r   r
   AV1HEVCr   get_lib_infoRuntimeErrorr   r   r   r   r*   rJ   r   updater   	add_imager   r    r,   r   r/   r   )r   r   r   compressioncompression_formatimages_to_saver   	ctx_writer]   r   rJ   r'   r'   r(   r   Q  s>   

r   	pil_imager8   c                 C  s   t  }||  |S )zCreates :py:class:`~pillow_heif.HeifFile` from a Pillow Image.

    :param pil_image: Pillow :external:py:class:`~PIL.Image.Image` class.

    :returns: New :py:class:`~pillow_heif.HeifFile` object.
    )r   r   )r   r>   r'   r'   r(   from_pillowp  s   
r   c                 K  s    t  }|j| ||fi | |S )aJ  Creates :py:class:`~pillow_heif.HeifFile` from bytes.

    .. note:: Supports ``stride`` value if needed.

    :param mode: see :ref:`image-modes`.
    :param size: tuple with ``width`` and ``height`` of an image.
    :param data: bytes object with raw image data.

    :returns: New :py:class:`~pillow_heif.HeifFile` object.
    )r   r   )r    r   r,   r   r>   r'   r'   r(   
from_bytes|  s   r   r   )TF)r-   r   )r    r   r   r   r-   r=   )r   r   r-   r=   )r   r8   r-   r   )r    r   r   r   r-   r   )1rD   
__future__r   r   r   ior   typingr   PILr   r   r	   	constantsr
   miscr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ImportErrorex_deffered_errorr   r   rG   rY   rZ   r   r   r   r   r   r   r   r   r'   r'   r'   r(   <module>   s<    HNS  



