
    e_                    l   d dl mZ d dlZd dlZd dlZd dlZd dlmZmZ ddl	m
Z
 ddlmZ ddlmZ dZd	Zd
Z	 ddddddZ	 d Zd Zd Z G d de      Z G d de
j                        Z G d de      Z G d d      Zd'dZd(d)dZd Z G d d       Z G d! d"      Z G d# d$e      Z G d% d&e      Z y)*    )annotationsN)Any
NamedTuple   )Image)	deprecate)is_pathi   i   Fzimage buffer overrun errorzdecoding errorzunknown errorzbad configurationzout of memory error)ic                   	 t         j                  j                  |       }|s|rdnd d|  }|d|rdnd dz  }t        |      S # t        $ r t        j                  |       }Y Ew xY w)Nencoderdecoderz error z when writingreadingz image file)r   coregetcodecstatusAttributeErrorERRORSgetOSError)errorr   msgs      //usr/lib/python3/dist-packages/PIL/ImageFile.py_get_oserrorr   C   sv     jj''. %95WUGDVIi8DDC3<   jj s   A A'&A'c                8    t        ddd       t        | d      )Nraise_oserror   zIt is only useful for translating error codes returned by a codec's decode() method, which ImageFile already does automatically.)actionFr   )r   r   )r   s    r   r   r   N   s%    
G ue
,,    c                    | d   S )N    )ts    r   	_tilesortr'   X   s    Q4Kr"   c                  6    e Zd ZU ded<   ded<   ded<   ded<   y	)
_Tilestrencoder_nameztuple[int, int, int, int]extentsintoffsetztuple[Any, ...] | str | NoneargsN)__name__
__module____qualname____annotations__r%   r"   r   r)   r)   ]   s    &&K
&&r"   r)   c                  R     e Zd ZdZd
 fd	Zd Z fdZd Zd Zd Z	d Z
d	 Z xZS )	ImageFilez*Base class for image file format handlers.c                ~   t         |           d| _        d | _        d | _        	 d| _        d| _        t        | _        t        |      r t        |d      | _        || _        d| _        n|| _        || _        d | _        	 	 | j                          | j,                  r$| j.                  d   dk  s| j.                  d   dk  rd}t+        |      y # t        t         t"        t$        t&        j(                  f$ r}t+        |      |d }~ww xY w# t0        $ r( | j                  r| j                  j3                           w xY w)Nr   r   r%   rbTznot identified by this driver)super__init__
_min_framecustom_mimetypetilereadonlydecoderconfigMAXBLOCKdecodermaxblockr	   openfpfilename_exclusive_fp_open
IndexError	TypeErrorKeyErrorEOFErrorstructr   SyntaxErrormodesizeBaseExceptionclose)selfrB   rC   vr   	__class__s        r   r9   zImageFile.__init__l   s'   #	7'2;2tnDGDM!%D DG$DM!%D		,

 99		! 1TYYq\Q5F5!#&& 6G  , "!n!+,  	!!		s*   C =D (D7DDD 1D<c                    | j                   r| j                   S | j                  7t        j                  j	                  | j                  j                               S y N)r;   formatr   MIMEr   upperrP   s    r   get_format_mimetypezImageFile.get_format_mimetype   sF    ''';;"::>>$++"3"3"566 #r"   c                2    g | _         t        | 	  |       y rT   )r<   r8   __setstate__)rP   staterR   s     r   r[   zImageFile.__setstate__   s    	U#r"   c                ^    | j                   r| j                  j                          d| _        y)zCheck file integrityN)rD   rB   rO   rX   s    r   verifyzImageFile.verify   s!    
 GGMMOr"   c                D
   | j                   d}t        |      t        j                  j                  |       }| j                   s|S d| _        | j
                  xr t        | j                         dk(  }|xr t        t        d       }d}	 | j                  }d}	 | j                  }d}|rU| j                   d   \  }}}	}
t        |
t               r|
ddf}
|dk(  r&t        |
      dk\  r|
d   | j"                  k(  r|
d   t        j$                  v r	 ddl}t)        | j
                        5 }|j'                  |j+                         d|j,                  	      | _        ddd       |	| j.                  d   |
d   z  z   | j                  j/                         kD  rd
}t        |      t        j0                  j3                  | j                  | j.                  ||	|
      | _        d}| j6                  rd| j6                  _        | j=                          d}| j                  s| j                   j?                  t@               	 | jB                  }tE        jF                  | j                   d       D cg c]  \  }}tI        |      d    c}}| _         | j                   D ]  \  }}}	}
 ||	       t        jJ                  | j"                  ||
| jL                        }	 |jO                  | j4                  |       |jP                  r0|jS                  | j                         |jU                  d      d   }n^|}	 	  || jV                        }|s!t^        rn?dt        |       d}t        |      ||z   }|jU                  |      \  }}|dk  rn||d }[|ja                           g | _         || _1        | je                          | jf                  r&| jh                  r| j                  jk                          d| _        | j                  st^        s|dk  rtm        |d      t        j                  j                  |       S # t        $ r | j                  j                  }Y w xY w# t        $ r | j                  j                  }Y w xY w# 1 sw Y   /xY w# t        t        t:        f$ r d| _        Y w xY w# t        $ r d}Y {w xY wc c}}w # tX        tZ        j\                  f$ r}t^        rY d}~ed}t        |      |d}~ww xY w# |ja                          w xY w)z"Load image data based on tile listNzcannot load this imager   pypy_version_infor   Fraw   )accesszbuffer is not large enoughr   keyr"   c                    | d   | d   | d   fS )Nr   r   rb   r%   )r<   s    r   <lambda>z ImageFile.load.<locals>.<lambda>   s    T!Wd1gtAw,G r"   r
   zimage file is truncatedzimage file is truncated (z bytes not processed)r!   )7r<   r   r   loadmaprC   lenhasattrsys	load_readr   rB   read	load_seekseek
isinstancer*   rL   	_MAPMODESmmaprA   filenoACCESS_READrM   r   
map_bufferimpalettedirtyImportErrorload_preparesortr'   tile_prefix	itertoolsgroupbylist_getdecoderr>   setimagepulls_fdsetfddecoder@   rF   rJ   r   LOAD_TRUNCATED_IMAGEScleanupr=   load_endrD   !_close_exclusive_fp_after_loadingrO   r   )rP   r   pixeluse_mmapr=   rn   rp   decoder_namer,   r.   r/   rs   rB   err_codeprefix_tilesr   bsens                         r   rh   zImageFile.load   s    99*C#,  &yyL==8S^q%8EGC1D$E E	 >>DH	 >>DH 26))A,/L'64$$a|%INGtyy(Gu.$dmm, V#'99RYY[!DDTDT9#UV		!tAw 66H:%cl*#jj33$))\64DG  !H ||-.* 	xxIINNyN))) !* 1 1IIG!Au UBDI 8<yy (&3gvtV++II|T43E3E#&$$TWWg6''dgg.#*>>##6q#9"">$()=)=$> $%#8$)),,/F83H)J %( +2#,$6 !AA*1..*;KAx 1u % !!"A3 #8 OO%Q(&T 	 $"H"HGGMMOxx 5(Q,x77{{%%e  	 77<<D	   	 77<<D	 $V V '= $#DH$ " * %/#= >#8$)*CC*1#,A$=>2 OO%s   P? Q% R ,2RB#R R: 1SAT8S
AT?Q"!Q"%RRRR R76R7:S	S	T
+T1T7TT

TTc                x   | j                   rF| j                   j                  | j                  k7  s#| j                   j                  | j                  k7  r9t        j                  j                  | j                  | j                        | _         | j                  dk(  r t        j                  j                  |        y y )NP)rw   rL   rM   r   r   newrh   rX   s    r   r{   zImageFile.load_prepare:  sp    ww$'',,$))3tww||tyy7PjjnnTYY		:DG99KKT" r"   c                     y rT   r%   rX   s    r   r   zImageFile.load_endB  s    r"   c                    || j                   k  s4t        | d      r| j                  )|| j                  | j                   z   k\  rd}t	        |      | j                         |k7  S )N	_n_framesz attempt to seek outside sequence)r:   rk   r   n_framesrI   tell)rP   framer   s      r   _seek_checkzImageFile._seek_checkN  sZ    DOO# T;/DNN4JT]]T__<< 5C3-yy{e##r"   )NN)r0   r1   r2   __doc__r9   rY   r[   r^   rh   r{   r   r   __classcell__)rR   s   @r   r5   r5   i   s1    4.`7$I&V#$r"   r5   c                  "    e Zd ZdZd Zd Zd Zy)StubImageFilez
    Base class for stub image loaders.

    A stub loader is an image loader that can identify files of a
    certain format, but relies on external code to load the file.
    c                    d}t        |      )Nz+StubImageFile subclass must implement _openNotImplementedErrorrP   r   s     r   rE   zStubImageFile._openf  s    ;!#&&r"   c                    | j                         }|d| j                   d}t        |      |j                  |       }|J |j                  | _        |j
                  | _        |j                         S )Nzcannot find loader for this z file)_loadrU   r   rh   rR   __dict__)rP   loaderr   images       r   rh   zStubImageFile.loadj  sj    >0UCC#,D!   zz|r"   c                    d}t        |      )z (Hook) Find actual image loader.z+StubImageFile subclass must implement _loadr   r   s     r   r   zStubImageFile._loadv  s    ;!#&&r"   N)r0   r1   r2   r   rE   rh   r   r%   r"   r   r   r   ^  s    '
'r"   r   c                  F    e Zd ZdZdZdZdZdZdZdZ	d Z
d Zd Zd Zd Zy)	Parserzj
    Incremental image parser.  This class implements the standard
    feed/close consumer interface.
    Nr   c                *    | j                   J d       y)z
        (Consumer) Reset the parser.  Note that you can only call this
        method immediately after you've created a parser; parser
        instances cannot be reused.
        Nzcannot reuse parsers)datarX   s    r   resetzParser.reset  s     yy 8"88 r"   c                T   | j                   ry| j                  || _        n| j                  |z   | _        | j                  r| j                  dkD  rmt	        t        | j                        | j                        }| j                  |d | _        | j                  |z
  | _        | j                  dkD  s| j                  sy| j                  j                  | j                        \  }}|dk  r(d| _        d| _         |dk  rd| _        t        |d      y| j                  |d | _        y| j                  ry	 t        j                  | j                        5 }t        j                  |      }ddd       t        d      xs t        |d      }|st        |j                        dk7  rd| _        || _        y|j                          |j                  d   \  }}}	}
g |_        t        j                   |j"                  ||
|j$                        | _        | j                  j'                  |j(                  |       |	| _        | j                  t        | j                        k  r%| j                  | j                  d | _        d| _        || _        y# 1 sw Y   %xY w# t*        $ r Y yw xY w)z
        (Consumer) Feed data to the parser.

        :param data: A string buffer.
        :exception OSError: If the parser failed to parse the image file.
        Nr   r   Fr!   ro   rm   )finishedr   r   r.   minrj   r   r   r   ioBytesIOr   rA   rk   r<   r{   r   rL   r>   r   rw   r   )rP   r   skipr   r   rB   rw   flagdoas              r   feedzParser.feed  s(    ==99DI		D(DI <<{{Q3tyy>4;;7 IIde,	"kkD0;;?$))<<&&tyy1DAq1u 	 !q5!%DJ&q%88 		!"DIZZ  ZZ		* (bBB(
 r;/K72{3K3rww<1,"&DK  
 OO%!#JAq!Q BG#(#4#4RWWaBDTDT#UDLLL))"%%3 #$DK{{c$))n4$(IIdkkm$<	&'
/( ( s*   6J J+J JJ 	J'&J'c                    | S rT   r%   rX   s    r   	__enter__zParser.__enter__  s    r"   c                $    | j                          y rT   )rO   rP   r/   s     r   __exit__zParser.__exit__  s    

r"   c                ,   | j                   r8| j                  d       dx| _        | _         | j                  sd}t	        |      | j
                  sd}t	        |      | j                  rjt        j                  | j                        5 }	 t        j                  |      | _        | j
                  j                          	 ddd       | j
                  S | j
                  S # | j
                  j                          w xY w# 1 sw Y   | j
                  S xY w)a  
        (Consumer) Close the stream.

        :returns: An image object.
        :exception OSError: If the parser failed to parse the image file either
                            because it cannot be identified or cannot be
                            decoded.
        r"   Nzimage was incompletezcannot parse this image)r   r   r   r   r   r   r   r   r   rA   rh   )rP   r   rB   s      r   rO   zParser.close  s     <<IIcN'++DI==,cl"zz+C#,99 DII& &"&!&BDJJJOO%	&
 zztzz JJOO%	&
 zzs$   	C?C %C? C<<C??D)r0   r1   r2   r   incrementalr   r   r   r.   r   r   r   r   r   rO   r%   r"   r   r   r   |  sB    
 KEDGFH9J Xr"   r   c           	        | j                          t        | d      sd| _        |j                  t               t        t        || j                  d   dz        }	 |j                         }|j                          t        | ||||       t        |d      r|j                          yy# t        t        j                  f$ r}t        | |||d|       Y d}~Ld}~ww xY w)zHelper to save image based on tile list

    :param im: Image object.
    :param fp: File object.
    :param tile: Tile list.
    :param bufsize: Optional buffer size
    encoderconfigr%   rd   r      Nflush)rh   rk   r   r|   r'   maxr?   rM   rt   r   _encode_tiler   r   UnsupportedOperation)rw   rB   r<   bufsizefhexcs         r   _saver     s     GGI2'II)I
 (GRWWQZ!^4G7YY[

RT7B/ r7

  B334 7RT7D#667s   /B) )CCCc                0   |D ]  \  }}}}	|dkD  r|j                  |       t        j                  | j                  ||	| j                        }
	 |
j                  | j                  |       |
j                  r%|
j                  |       |
j                         d   }nA|r-	 |
j                  |      dd  \  }}|j                  |       |rn,|
j                  ||      }|dk  rt        |d      |	 |
j                           y # |
j                          w xY w)Nr   r   Tr!   )rp   r   _getencoderrL   r   r   rw   	pushes_fdr   encode_to_pyfdencodewriteencode_to_filer   r   )rw   rB   r<   r   r   r   r+   r,   r.   r/   r   errcoder   s                r   r   r   !  s   /3 +gvtA:GGFO##BGG\4AQAQR	RUUG,  b!!00215(/w(?(C"!	  &44RAG{"7D9sB  OO/. OOs   B!DDc                   |dk  ry|t         k  r.| j                  |      }t        |      |k  rd}t        |      |S g }|}|dkD  rG| j                  t	        |t                     }|sn%|j                  |       |t        |      z  }|dkD  rGt        d |D              |k  rd}t        |      dj                  |      S )a  
    Reads large blocks in a safe way.  Unlike fp.read(n), this function
    doesn't trust the user.  If the requested size is larger than
    SAFEBLOCK, the file is read block by block.

    :param fp: File handle.  Must implement a <b>read</b> method.
    :param size: Number of bytes to read.
    :returns: A string containing <i>size</i> bytes of data.

    Raises an OSError if the file is truncated and the read cannot be completed

    r   r"   zTruncated File Readc              3  2   K   | ]  }t        |        y wrT   )rj   ).0r   s     r   	<genexpr>z_safe_read.<locals>.<genexpr>Y  s     
 a3q6
 s   )	SAFEBLOCKrn   rj   r   r   appendsumjoin)rB   rM   r   r   remaining_sizeblocks         r   
_safe_readr   <  s     qyywwt}t9t'C#,DN
1
NI67E#e*$ 1
 
 4
  4'#cl88D>r"   c                      e Zd Zd Zd Zy)PyCodecStatec                <    d| _         d| _        d| _        d| _        y )Nr   )xsizeysizexoffyoffrX   s    r   r9   zPyCodecState.__init__`  s    

		r"   c                    | j                   | j                  | j                   | j                  z   | j                  | j                  z   fS rT   )r   r   r   r   rX   s    r   r,   zPyCodecState.extentsf  s3    yy$))TYY%;TYY=SSSr"   N)r0   r1   r2   r9   r,   r%   r"   r   r   r   _  s    Tr"   r   c                  ,    e Zd Zd Zd Zd Zd ZddZy)PyCodecc                n    d | _         t               | _        d | _        || _        | j                  |       y rT   )rw   r   r\   fdrL   init)rP   rL   r/   s      r   r9   zPyCodec.__init__k  s+    !^
			$r"   c                    || _         y)z
        Override to perform codec specific initialization

        :param args: Array of args items from the tile entry
        :returns: None
        N)r/   r   s     r   r   zPyCodec.initr  s     	r"   c                     y)zT
        Override to perform codec specific cleanup

        :returns: None
        Nr%   rX   s    r   r   zPyCodec.cleanup{  s     	r"   c                    || _         y)z
        Called from ImageFile to set the Python file-like object

        :param fd: A Python file-like object
        :returns: None
        N)r   )rP   r   s     r   r   zPyCodec.setfd  s     r"   Nc                    || _         |r|\  }}}}nd\  }}}}|dk(  r=|dk(  r8| j                   j                  \  | j                  _        | j                  _        nJ|| j                  _        || j                  _        ||z
  | j                  _        ||z
  | j                  _        | j                  j                  dk  s| j                  j                  dk  rd}t        |      | j                  j                  | j                  j
                  z   | j                   j                  d   kD  sG| j                  j                  | j                  j                  z   | j                   j                  d   kD  rd}t        |      y)z
        Called from ImageFile to set the core output image for the codec

        :param im: A core image object
        :param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectangle
            for this tile
        :returns: None
        )r   r   r   r   r   zSize cannot be negativer   z Tile cannot extend outside imageN)rw   rM   r\   r   r   r   r   
ValueError)rP   rw   r,   x0y0x1y1r   s           r   r   zPyCodec.setimage  s,    &RR+RR7rQw15.DJJdjj. DJJO DJJO!BwDJJ!BwDJJ::q DJJ$4$4$9+CS/! JJtzz.a@zz$**//1DGGLLOC4CS/! Dr"   rT   )r0   r1   r2   r9   r   r   r   r   r%   r"   r   r   r   j  s    #"r"   r   c                  2    e Zd ZdZdZed        Zd ZddZy)	PyDecoderz
    Python implementation of a format decoder. Override this class and
    add the decoding logic in the :meth:`decode` method.

    See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`
    Fc                    | j                   S rT   )	_pulls_fdrX   s    r   r   zPyDecoder.pulls_fd  s    ~~r"   c                    d}t        |      )a=  
        Override to perform the decoding process.

        :param buffer: A bytes object with the data to be decoded.
        :returns: A tuple of ``(bytes consumed, errcode)``.
            If finished with decoding return -1 for the bytes consumed.
            Err codes are from :data:`.ImageFile.ERRORS`.
        zunavailable in base decoderr   )rP   bufferr   s      r   r   zPyDecoder.decode       ,!#&&r"   Nc                @   |s| j                   }t        j                  | j                   d|      }|j                  | j                  | j
                  j                                |j                  |      }|d   dk\  rd}t        |      |d   dk7  rd}t        |      y)a  
        Convenience method to set the internal image from a stream of raw data

        :param data: Bytes to be set
        :param rawmode: The rawmode to be used for the decoder.
            If not specified, it will default to the mode of the image
        :returns: None
        ra   r   znot enough image datar   zcannot decode image dataN)	rL   r   r   r   rw   r\   r,   r   r   )rP   r   rawmoder   r   r   s         r   
set_as_rawzPyDecoder.set_as_raw  s     iiGdii8	

477DJJ..01HHTNQ419)CS/!Q419,CS/! r"   rT   )	r0   r1   r2   r   r   propertyr   r   r  r%   r"   r   r   r     s*     I 
'"r"   r   c                  6    e Zd ZdZdZed        Zd Zd Zd Z	y)	PyEncoderz
    Python implementation of a format encoder. Override this class and
    add the decoding logic in the :meth:`encode` method.

    See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`
    Fc                    | j                   S rT   )
_pushes_fdrX   s    r   r   zPyEncoder.pushes_fd  s    r"   c                    d}t        |      )a   
        Override to perform the encoding process.

        :param bufsize: Buffer size.
        :returns: A tuple of ``(bytes encoded, errcode, bytes)``.
            If finished with encoding return 1 for the error code.
            Err codes are from :data:`.ImageFile.ERRORS`.
        zunavailable in base encoderr   )rP   r   r   s      r   r   zPyEncoder.encode  r   r"   c                    | j                   sy| j                  d      \  }}}|r| j                  j                  |       ||fS )z
        If ``pushes_fd`` is ``True``, then this method will be used,
        and ``encode()`` will only be called once.

        :returns: A tuple of ``(bytes consumed, errcode)``.
            Err codes are from :data:`.ImageFile.ERRORS`.
        )r   r   r   )r   r   r   r   )rP   bytes_consumedr   r   s       r   r   zPyEncoder.encode_to_pyfd  s@     ~~(,A%GGMM$w&&r"   c                |    d}|dk(  r4| j                  |      \  }}}|dkD  r|j                  ||d        |dk(  r4|S )z
        :param fh: File handle.
        :param bufsize: Buffer size.

        :returns: If finished successfully, return 0.
            Otherwise, return an error code. Err codes are from
            :data:`.ImageFile.ERRORS`.
        r   N)r   r   )rP   r   r   r   statusbufs         r   r   zPyEncoder.encode_to_file  sN     l#';;w#7 FGSzVW& l r"   N)
r0   r1   r2   r   r  r  r   r   r   r   r%   r"   r   r  r    s/     J 
''r"   r  )r   rT   )r<   zlist[_Tile])!
__future__r   r   r~   rJ   rl   typingr   r    r   
_deprecater   _utilr	   r?   r   r   r   r   r   r'   r)   r5   r   r   r   r   r   r   r   r   r  r%   r"   r   <module>r     s   : # 	   
 "  ! 	  N 	%
-
'J 'r$ r$j'I '<C CR86 FT TE" E"P/" /"d7 7r"   