
    0-Ph.W                         d Z ddlZddl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 ddlZddlmZmZmZmZmZ ddlmZ ddlmZmZmZmZ dd	lmZm Z  dd
lm!Z! dee"         fdZ#de"de$defdZ% G d de           Z&dS )a   Read/Write images using Pillow/PIL.

Backend Library: `Pillow <https://pillow.readthedocs.io/en/stable/>`_

Plugin that wraps the the Pillow library. Pillow is a friendly fork of PIL
(Python Image Library) and supports reading and writing of common formats (jpg,
png, gif, tiff, ...). For, the complete list of features and supported formats
please refer to pillows official docs (see the Backend Library link).

Parameters
----------
request : Request
    A request object representing the resource to be operated on.

Methods
-------

.. autosummary::
    :toctree: _plugins/pillow

    PillowPlugin.read
    PillowPlugin.write
    PillowPlugin.iter
    PillowPlugin.get_meta

    N)BytesIO)	AnyCallableDictIteratorListOptionalTupleUnioncast)ExifTagsGifImagePluginImageImageSequenceUnidentifiedImageError)__version__   )	URI_BYTESInitializationErrorIOModeRequest)ImagePropertiesPluginV3)	ArrayLikereturnc                  X    t          d t          j        d          D                       S )Nc              3   4   K   | ]}t          |          V  d S N)int).0xs     V/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/imageio/plugins/pillow.py	<genexpr>z!pillow_version.<locals>.<genexpr>.   s(      88AQ888888    .)tuplepil_versionsplit r$   r"   pillow_versionr*   -   s*    88!23!7!7888888r$   orientationmodec           	          t          j        |          dk    rdndd fdd fdfdd	 fd
d d}||          S )N   c                     | S r   r)   r!   s    r"   <lambda>z-_exif_orientation_transform.<locals>.<lambda>9   s    Q r$   c                 0    t          j        |           S )Naxisnpflipr!   r6   s    r"   r3   z-_exif_orientation_transform.<locals>.<lambda>:   s    RWQT*** r$   c                 .    t          j        | d          S )Nr   kr8   rot90r2   s    r"   r3   z-_exif_orientation_transform.<locals>.<lambda>;       RXa1%%% r$   c                 6    t          j        | dz
            S )Nr.   r5   r7   r:   s    r"   r3   z-_exif_orientation_transform.<locals>.<lambda><   s    RWQTAX... r$   c                 X    t          j        t          j        | d                    S )N   r<   r5   r8   r9   r?   r:   s    r"   r3   z-_exif_orientation_transform.<locals>.<lambda>=   %    RWRXa1---D999 r$   c                 .    t          j        | d          S )NrC   r<   r>   r2   s    r"   r3   z-_exif_orientation_transform.<locals>.<lambda>>   r@   r$   c                 X    t          j        t          j        | d                    S )Nr.   r<   r5   rD   r:   s    r"   r3   z-_exif_orientation_transform.<locals>.<lambda>?   rE   r$   c                 .    t          j        | d          S )Nr.   r<   r>   r2   s    r"   r3   z-_exif_orientation_transform.<locals>.<lambda>@   r@   r$   )r.   r   rC                  )r   getmodebands)r+   r,   EXIF_ORIENTATIONr6   s      @r"   _exif_orientation_transformrP   1   s    
 #D))A--222D ;****%%....9999%%9999%%	 	 K((r$   c                   ~    e Zd Zdeddf fdZd!dZdddddddddd	ed
ededededededede	j
        fdZdddddd
ededededee	j
                 f
dZde	j
        fdZdddddeeee         f         d
edededee         f
dZd Zdddeeef         fdZ	 d"d	ededeeef         fdZd#d	edefd Z xZS )$PillowPluginrequestr   Nc                    t                                          |           	 ddlm}  |             n# t          $ r Y nw xY w	 ddlm}  |             n# t          $ r Y nw xY wd| _        g | _        |j        j	        t          j        k    r	 t          j        |                                          5  	 ddd           n# 1 swxY w Y   nG# t          $ r: |j        t"          k    rt%          d          dt%          d|j         d          dw xY wt          j        | j                                                  | _        dS i | _        | j        j        p| j        j        }|t3          j        dt6                     dS t          j        t          j        g}|D ]6} |             |t          j                                                    v r dS 7t%          d	| d
          d)zInstantiate a new Pillow Plugin Object

        Parameters
        ----------
        request : {Request}
            A request object representing the resource to be operated on.

        r   )register_heif_opener)register_avif_openerNz'Pillow can not read the provided bytes.zPillow can not read r%   zCan't determine file format to write as. You _must_ set `format` during write or the call will fail. Use `extension` to supress this warning. zPillow can not write `z` files.) super__init__pillow_heifrU   ImportErrorrV   _imageimages_to_writer,   io_moder   readr   openget_filer   	_uri_typer   r   raw_uri_request	save_argsrS   	extensionformat_hintwarningswarnUserWarningpreinitinitregistered_extensionskeys)selfrS   rU   rV   re   tirageformat_loader	__class__s          r"   rX   zPillowPlugin.__init__G   s    	!!!	#888888 ! """"  	 	 	D		#888888 ! """"  	 	 	D	
 "!<6;.. Z 0 0 2 233   	              
 *      $	11-A   .AwAAA     *T]%;%;%=%=>>DKKKDN.J$,2JI <  	   mUZ0F!'   ; = = B B D DDDFF E &<<<< sR   5 
AAA 
A$#A$&C 6C8C CC CC ADc                     |                                   | j        r| j                                         | j                                         d S r   )_flush_writerr[   closerc   finish)rn   s    r"   rt   zPillowPlugin.close   sL    ; 	 Kr$   FT)indexr,   rotateapply_gammawriteable_outputpilmode
exifrotateas_grayrv   r,   rw   rx   ry   rz   r{   r|   c                l   |t          j        dt                     |}|t          j        dt                     |}|t          d          | j        j        dk    rt          j        j        t          _	        |2| j        j        dk    rt          }n| j        j        dk    rt          }nd}t          |t                    r9| j                            |           |                     | j        ||||          }	n9|                     ||||          }
t#          j        d	 |
D             d
          }	|	S )aW	  
        Parses the given URI and creates a ndarray from it.

        Parameters
        ----------
        index : int
            If the ImageResource contains multiple ndimages, and index is an
            integer, select the index-th ndimage from among them and return it.
            If index is an ellipsis (...), read all ndimages in the file and
            stack them along a new batch dimension and return them. If index is
            None, this plugin reads the first image of the file (index=0) unless
            the image is a GIF or APNG, in which case all images are read
            (index=...).
        mode : str
            Convert the image to the given mode before returning it. If None,
            the mode will be left unchanged. Possible modes can be found at:
            https://pillow.readthedocs.io/en/stable/handbook/concepts.html#modes
        rotate : bool
            If True and the image contains an EXIF orientation tag,
            apply the orientation before returning the ndimage.
        apply_gamma : bool
            If True and the image contains metadata about gamma, apply gamma
            correction to the image.
        writable_output : bool
            If True, ensure that the image is writable before returning it to
            the user. This incurs a full copy of the pixel data if the data
            served by pillow is read-only. Consequentially, setting this flag to
            False improves performance for some images.
        pilmode : str
            Deprecated, use `mode` instead.
        exifrotate : bool
            Deprecated, use `rotate` instead.
        as_gray : bool
            Deprecated. Exists to raise a constructive error message.

        Returns
        -------
        ndimage : ndarray
            A numpy array containing the loaded image data

        Notes
        -----
        If you read a paletted image (e.g. GIF) then the plugin will apply the
        palette by default. Should you wish to read the palette indices of each
        pixel use ``mode="P"``. The coresponding color pallete can be found in
        the image's metadata using the ``palette`` key when metadata is
        extracted using the ``exclude_applied=False`` kwarg. The latter is
        needed, as palettes are applied by default and hence excluded by default
        to keep metadata and pixel data consistent.

        Nz,`pilmode` is deprecated. Use `mode` instead.z1`exifrotate` is deprecated. Use `rotate` instead.zThe keyword `as_gray` is no longer supported.Use `mode='F'` for a backward-compatible result, or  `mode='L'` for an integer-valued result.GIF
image/apngr   r,   rw   rx   ry   c                     g | ]}|S r)   r)   )r    ims     r"   
<listcomp>z%PillowPlugin.read.<locals>.<listcomp>  s    444Rb444r$   r5   )rg   rh   DeprecationWarning	TypeErrorr[   formatr   LoadingStrategy RGB_AFTER_DIFFERENT_PALETTE_ONLYLOADING_STRATEGYEllipsiscustom_mimetype
isinstancer   seek_apply_transformsiterr8   stack)rn   rv   r,   rw   rx   ry   rz   r{   r|   imageiterators              r"   r^   zPillowPlugin.read   sl   @ M>@R   D!MCEW    F<   ;&& .O + ={!U** ,<< eS!! 	>KU###**T6;8H EE yy'!1	 !  H H4484441===Er$   r   c             #   x   K   t          j        | j                  D ]}|                     |||||          V  dS )a  
        Iterate over all ndimages/frames in the URI

        Parameters
        ----------
        mode : {str, None}
            Convert the image to the given mode before returning it. If None,
            the mode will be left unchanged. Possible modes can be found at:
            https://pillow.readthedocs.io/en/stable/handbook/concepts.html#modes
        rotate : {bool}
            If set to ``True`` and the image contains an EXIF orientation tag,
            apply the orientation before returning the ndimage.
        apply_gamma : {bool}
            If ``True`` and the image contains metadata about gamma, apply gamma
            correction to the image.
        writable_output : bool
            If True, ensure that the image is writable before returning it to
            the user. This incurs a full copy of the pixel data if the data
            served by pillow is read-only. Consequentially, setting this flag to
            False improves performance for some images.
        N)r   r   r[   r   )rn   r,   rw   rx   ry   r   s         r"   r   zPillowPlugin.iter
  sa      <  (55 	 	B((D&+/?     	 	r$   c                    ||                     |          }n|j        dk    r |                     |j        j                  }n|j        dk    rv|j        dk    rkt	                      \  }}}t
          j        dk    rd}	nd}	|dk     rt          j        dt                     n#|d	k     r|	|_        n|                     |	          }t          j        |          }|                     | j                                        d
          }
|r/d|
v r+t          |
d         | j        j                  } ||          }|rd|
v rt!          |
d                   }t!          |j        t          j        k    rdnd          }d}||z  |z  |z  |z  dz   }t          j        |                              t          j                  }|r!|j        d         st          j        |          }|S )NPPNGIlittlezI;16zI;16B
   zLoading 16-bit (uint16) PNG as int32 due to limitations in pillow's PNG decoder. This will be fixed in a future version of pillow which will make this warning dissapear.r.   Frv   exclude_appliedOrientationgammai      g      ?g<Nё\?	WRITEABLE)convertr,   paletter   r*   sys	byteorderrg   rh   ri   r8   asarraymetadatar[   tellrP   floatdtypeuint16roundastypeuint8flagsarray)rn   r   r,   rw   rx   ry   majorminorpatchdesired_modemetatransformationr   scalegains                  r"   r   zPillowPlugin._apply_transforms-  s    MM$''EEZ3 MM%-"455EE\U""uzS'8'8"0"2"2E5%}((%  'rzzP  	    )

 l33
5!!}}4;#3#3#5#5u}MM 	*mt++8]#T[%5 N #N5))E 	57d??$w-((E5;")#;#;%%EEEDem-6=FEHUOO**2844E 	$EK$< 	$HUOOEr$   )r,   r   is_batchndimager   r   c                   d|v r5t          j        dt                     d|                    d          z  |d<   t	          |t
                    rt          j        |d          }d}nt          j        |          }|n|/t          j
        |          d	k    r|j        d
k    n
|j        dk    }nX|j        dk    rd}nJ|j        d
k    r |j        d         d	k    rt          d          |j        d
k    r|j        d         dv rd}nd}|s|d         }|D ]U}t          j        ||          }d|v r|                    d|d         z            }| j                            |           V|Hd| j        v r?| j        d         |k    r.| j        d         }t          j        d| d| dt&                     | j        j        p| j        j        }	|pt          j                    |	         | j        d<   | j                            |           d}
| j        j        t6          k    rT|                                  t;          t<          | j                                                  }|                                 }
|
S )aH  
        Write an ndimage to the URI specified in path.

        If the URI points to a file on the current host and the file does not
        yet exist it will be created. If the file exists already, it will be
        appended if possible; otherwise, it will be replaced.

        If necessary, the image is broken down along the leading dimension to
        fit into individual frames of the chosen format. If the format doesn't
        support multiple frames, and IOError is raised.

        Parameters
        ----------
        image : ndarray or list
            The ndimage to write. If a list is given each element is expected to
            be an ndimage.
        mode : str
            Specify the image's color format. If None (default), the mode is
            inferred from the array's shape and dtype. Possible modes can be
            found at:
            https://pillow.readthedocs.io/en/stable/handbook/concepts.html#modes
        format : str
            Optional format override. If omitted, the format to use is
            determined from the filename extension. If a file object was used
            instead of a filename, this parameter must always be used.
        is_batch : bool
            Explicitly tell the writer that ``image`` is a batch of images
            (True) or not (False). If None, the writer will guess this from the
            provided ``mode`` or ``image.shape``. While the latter often works,
            it may cause problems for small images due to aliasing of spatial
            and color-channel axes.
        kwargs : ...
            Extra arguments to pass to pillow. If a writer doesn't recognise an
            option, it is silently ignored. The available options are described
            in pillow's `image format documentation
            <https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html>`_
            for each writer.

        Notes
        -----
        When writing batches of very narrow (2-4 pixels wide) gray images set
        the ``mode`` explicitly to avoid the batch being identified as a colored
        image.

        fpszvThe keyword `fps` is no longer supported. Use `duration`(in ms) instead, e.g. `fps=50` == `duration=20` (1000 * 1/50).i  durationr   r5   TNr.   rC   r   Fr0   z*Can't write images with one color channel.)r   rC   rI   )N.)r,   bits)colorsr   zSChanging the output format during incremental writes is strongly discouraged. Was `z`, is now `z`.)!rg   rh   r   getr   listr8   r   r   r   rN   ndimshape
ValueError	fromarrayquantizer\   appendrd   ri   rS   re   rf   rl   updaterc   ra   r   rs   r   r   r`   getvalue)rn   r   r,   r   r   kwargsframe	pil_frame
old_formatre   resultfiles               r"   writezPillowPlugin.writeb  s   l F??MQ"  
 "*FJJu,=,=!=F:gt$$ 	*hwQ///GHHj))G $)$6t$<$<q$@$@q  glUVFV H \QHH\Q7=#4#9#9IJJJ\Q7=#4	#A#AHHH 	)i(G 	3 	3ED999I%..a6&>6I.JJ	 ''	2222 DN**x(F221JM;#; ;06; ; ; 	   L*Fdl.F	#)#UU-H-J-J9-Ux f%%% ="i//   !7!7!9!9::D]]__Fr$   c                    t          | j                  dk    rd S | j                            d          }t          | j                  dk    rd| j        d<   | j        | j        d<    |j        | j                                        fi | j         | j                                         | j                                         d S )Nr   Tsave_allappend_images)lenr\   poprd   saverc   r`   clear)rn   primary_images     r"   rs   zPillowPlugin._flush_writer  s    t#$$))F,0033t#$$q(()-DN:&.2.BDN?+4=1133FFt~FFF""$$$r$   r   )rv   c                0    |                      |d          S )NFr   )r   )rn   rv   s     r"   get_metazPillowPlugin.get_meta  s    }}5%}@@@r$   r   c                 h   |2| j         j        dk    rt          }n| j         j        dk    rt          }nd}t	          |t
                    r7| j                                         |k    r| j                             |           | j         j        	                                }| j         j
        |d<   | j         j        |d<   | j         j
        dk    rG|sEt          j        t          | j         j        j                                                            |d<   | j                                         rmd	 t'          | j                                                                                   D             }|                    d
d           |                    |           |r|                    dd           |S )a  Read ndimage metadata.

        Parameters
        ----------
        index : {integer, None}
            If the ImageResource contains multiple ndimages, and index is an
            integer, select the index-th ndimage from among them and return its
            metadata. If index is an ellipsis (...), read and return global
            metadata. If index is None, this plugin reads metadata from the
            first image of the file (index=0) unless the image is a GIF or APNG,
            in which case global metadata is read (index=...).
        exclude_applied : bool
            If True, exclude metadata fields that are applied to the image while
            reading. For example, if the binary data contains a rotation flag,
            the image is rotated by default and the rotation flag is excluded
            from the metadata to avoid confusion.

        Returns
        -------
        metadata : dict
            A dictionary of format-specific metadata.

        Nr~   r   r   r,   r   r   r   c                 V    i | ]&\  }}t           j                            |d           |'S )unknown)r   TAGSr   )r    keyvalues      r"   
<dictcomp>z)PillowPlugin.metadata.<locals>.<dictcomp>  s@       C !!#y115  r$   r   r   )r[   r   r   r   r   r   r   r   infocopyr,   sizer8   r   r&   r   r   rm   getexifdictitemsr   r   )rn   rv   r   r   	exif_datas        r"   r   zPillowPlugin.metadata  s   6 ={!U** ,<< eS!! 	$dk&6&6&8&8E&A&AKU###;#((**;+ K,;s""?""$*U4;3F3M3R3R3T3T-U-U"V"VHY;   	' "&t{':':'<'<"="="C"C"E"E  I MM)T***OOI&&& 	.LL---r$   c                    |2| j         j        dk    rt          }n| j         j        dk    rt          }nd}|t          u r| j                             d           n| j                             |           | j         j        dk    r| j         j        j        }n| j         j        }| j         j        }| j         j        }||f}d}|du rt          | j         dd          }|g|R }t          j        t          j        |d	                    }|j        }t          |          d
k    rg ||d
d         R }t!          ||j        ||t          u           S )a  Standardized ndimage metadata
        Parameters
        ----------
        index : int
            If the ImageResource contains multiple ndimages, and index is an
            integer, select the index-th ndimage from among them and return its
            properties. If index is an ellipsis (...), read and return the
            properties of all ndimages in the file stacked along a new batch
            dimension. If index is None, this plugin reads and returns the
            properties of the first image (index=0) unless the image is a GIF or
            APNG, in which case it reads and returns the properties all images
            (index=...).

        Returns
        -------
        properties : ImageProperties
            A dataclass filled with standardized image metadata.

        Notes
        -----
        This does not decode pixel data and is fast for large images.

        Nr~   r   r   r   .n_framesr.   )r.   r.   r   )r   r   n_imagesr   )r[   r   r   r   r   r,   r   widthheightgetattrr8   r   r   newr   r   r   r   )	rn   rv   r,   r   r   r   r   dummy	pil_shapes	            r"   
propertieszPillowPlugin.properties&  sd   2 ={!U** ,<< HKQKU###;s"";&+DD;#D[&k("(%"&C<<t{J::H&&&E
59T62233%*[	y>>A,e,im,,E+h&	
 
 
 	
r$   )r   N)NTr   )__name__
__module____qualname__r   rX   rt   r   strboolr8   ndarrayr^   r   r   r   r   r   r   r	   bytesr   rs   r   r   r   r   r   r   __classcell__)rq   s   @r"   rR   rR   F   s       F FD F F F F F FP    !!%q q q q 	q
 q q q q q q 
q q q ql !!%! ! ! ! 	!
 ! ! 
"*	! ! ! !F3	3 3 3 3r w w wy$y/12w 	w
 w w 
%w w w wr   !" A A Ad38n A A A A :>8 88268	c3h8 8 8 8t?
 ?
 ?
 ?
 ?
 ?
 ?
 ?
 ?
 ?
 ?
r$   rR   )'__doc__r   rg   ior   typingr   r   r   r   r   r	   r
   r   r   numpyr8   PILr   r   r   r   r   r   r'   core.requestr   r   r   r   core.v3_plugin_apir   r   r   r   r*   r   rP   rR   r)   r$   r"   <module>r      s   6 


        T T T T T T T T T T T T T T T T T T T T T T     V V V V V V V V V V V V V V * * * * * * J J J J J J J J J J J J : : : : : : : :      9c
 9 9 9 9)S ) ) ) ) ) )*_
 _
 _
 _
 _
8 _
 _
 _
 _
 _
r$   