U
    Evfe_                     @  s@  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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d Zdd Zdd ZG dd de	ZG dd dejZG dd deZG dd dZd1dd d!d"Zd2d#d$d%d&Zd'd( ZG d)d* d*ZG d+d, d,ZG d-d. d.eZ G d/d0 d0eZ!dS )3    )annotationsN)IOAny
NamedTuple   )Image)	deprecate)is_pathi   i   Fzimage buffer overrun errorzdecoding errorzunknown errorzbad configurationzout of memory error)ic                C  sj   zt j| }W n tk
r.   t| }Y nX |sJ|r<dnd d|  }|d|rVdnd d7 }t|S )Nencoderdecoderz error z when writingreadingz image file)r   coreZgetcodecstatusAttributeErrorERRORSgetOSError)errorr   msg r   1/tmp/pip-unpacked-wheel-ciywl2yd/PIL/ImageFile.py_get_oserrorC   s    r   c                 C  s   t dddd t| ddd S )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   r   r   r   r   N   s    r   c                 C  s   | d S )N   r   )tr   r   r   	_tilesortX   s    r"   c                   @  s.   e Zd ZU ded< ded< ded< ded< d	S )
_TilestrZ
codec_nameztuple[int, int, int, int]extentsintoffsetztuple[Any, ...] | str | NoneargsN)__name__
__module____qualname____annotations__r   r   r   r   r#   ]   s   
r#   c                      s^   e Zd ZdZd fdd	Zdd Z fddZd	d
 Zdd Zdd Z	dd Z
dd Z  ZS )	ImageFilez*Base class for image file format handlers.Nc                   s  t    d| _d | _d | _d| _d| _t| _t	|rPt
|d| _|| _d| _n|| _|| _d | _zxz|   W n8 tttttjfk
r } zt||W 5 d }~X Y nX | jr| jd dks| jd dkrd}t|W n( tk
r   | jr| j   Y nX d S )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)selfr9   r:   vr   	__class__r   r   r0   l   s@    
"
zImageFile.__init__c                 C  s,   | j r| j S | jd k	r(tj| j S d S N)r2   formatr   ZMIMEr   upperrG   r   r   r   get_format_mimetype   s    
zImageFile.get_format_mimetypec                   s   g | _ t | d S rK   )r3   r/   __setstate__)rG   staterI   r   r   rP      s    zImageFile.__setstate__c                 C  s   | j r| j  d| _dS )zCheck file integrityN)r;   r9   rF   rN   r   r   r   verify   s    
zImageFile.verifyc                 C  s  | j dkrd}t|tj| }| j s,|S d| _| joDt| j dk}|oTttd }d}z| j	}d}W n t
k
r   | jj}Y nX z| j}d}W n t
k
r   | jj}Y nX |r| j d \}}}	}
t|
tr|
ddf}
|dkrt|
dkr|
d | jkr|
d tjkrzddl}t| j}|j| d|jd	| _W 5 Q R X |	| jd |
d   | j kr|d
}t|tj| j| j||	|
| _d}| jrd| j_W n" t
ttfk
r   d| _Y nX |   d}| jsh| j jt d z
| j!}W n t
k
r   d}Y nX dd t"#| j dd D | _ | j D ](\}}}	}
||	 t$| j||
| j%}z|'| j| |j(r|)| j |*dd }n|}z|| j+}W nJ t,t-j.fk
r } z$t/rW Y qVnd}t||W 5 d}~X Y nX |s"t/r
qVndt| d}t||| }|*|\}}|dk rFqV||d }qW 5 |&  X q<g | _ || _0| 1  | j2r| j3r| j4  d| _| jst/s|dk rt5|ddtj| S )z"Load image data based on tile listNzcannot load this imager   pypy_version_infor   Fraw   )accesszbuffer is not large enoughr   key    c                 S  s   g | ]\}}t |d  qS )r
   )list).0_Ztilesr   r   r   
<listcomp>   s   z"ImageFile.load.<locals>.<listcomp>c                 S  s   | d | d | d fS )Nr   r   rU   r   r3   r   r   r   <lambda>   rY   z ImageFile.load.<locals>.<lambda>zimage file is truncatedzimage file is truncated (z bytes not processed)r   )6r3   r   r   loadmapr:   lenhasattrsys	load_readr   r9   read	load_seekseek
isinstancer$   rC   Z	_MAPMODESmmapr8   filenoZACCESS_READrD   r   Z
map_bufferimZpaletteZdirtyImportErrorload_preparesortr"   Ztile_prefix	itertoolsgroupby_getdecoderr5   cleanupsetimagepulls_fdsetfddecoder7   r=   rA   r   LOAD_TRUNCATED_IMAGESr4   load_endr;   Z!_close_exclusive_fp_after_loadingrF   r   )rG   r   ZpixelZuse_mmapr4   rf   rh   Zdecoder_namer%   r'   r(   rj   r9   Zerr_codeprefixr   bsenr   r   r   r`      s    



""    

    

zImageFile.loadc                 C  sP   | j r"| j j| jks"| j j| jkr6tj| j| j| _ | jdkrLtj|  d S )NP)rl   rC   rD   r   r   newr`   rN   r   r   r   rn   :  s    "
zImageFile.load_preparec                 C  s   d S rK   r   rN   r   r   r   ry   B  s    zImageFile.load_endc                 C  sF   || j k s.t| dr| jd ks:|| j| j  kr:d}t||  |kS )N	_n_framesz attempt to seek outside sequence)r1   rc   r   Zn_framesr@   tell)rG   framer   r   r   r   _seek_checkN  s    	zImageFile._seek_check)NN)r)   r*   r+   __doc__r0   rO   rP   rR   r`   rn   ry   r   __classcell__r   r   rI   r   r-   i   s   0	 r-   c                   @  s(   e Zd ZdZdd Zdd Zdd ZdS )	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                 C  s   d}t |d S )Nz+StubImageFile subclass must implement _openNotImplementedErrorrG   r   r   r   r   r<   f  s    zStubImageFile._openc                 C  sT   |   }|d kr&d| j d}t||| }|d k	s<t|j| _|j| _| S )Nzcannot find loader for this z file)_loadrL   r   r`   AssertionErrorrJ   __dict__)rG   loaderr   imager   r   r   r`   j  s    
zStubImageFile.loadc                 C  s   d}t |dS )z (Hook) Find actual image loader.z+StubImageFile subclass must implement _loadNr   r   r   r   r   r   v  s    zStubImageFile._loadN)r)   r*   r+   r   r<   r`   r   r   r   r   r   r   ^  s   r   c                   @  sZ   e Zd ZU dZdZdZded< dZdZdZ	dZ
dd Zdd	 Zd
d Zdd Zdd ZdS )Parserzj
    Incremental image parser.  This class implements the standard
    feed/close consumer interface.
    NzImage.Image | Noner   r   c                 C  s   | j dkstddS )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)datar   rN   r   r   r   reset  s    zParser.resetc              	   C  s  | j r
dS | jdkr|| _n| j| | _| jr| jdkrztt| j| j}| j|d | _| j| | _| jdksv| jszdS | j| j\}}|dk rd| _d| _ |dk rd| _t|ddndS | j|d | _n| jrnz&t	
| j}t|}W 5 Q R X W n tk
r   Y nX t|dp,t|d}|sDt|jdkrLd| _nv|  |jd \}}}	}
g |_t|j||
|j| _| j|j| |	| _| jt| jkr| j| jd | _d| _|| _dS )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   rg   re   )finishedr   r   r'   minrb   rw   r   r   ioBytesIOr   r8   r   rc   r3   rn   rr   rC   r5   rt   rl   )rG   r   skipr~   r}   r9   rl   flagdoar   r   r   feed  sR    	

zParser.feedc                 C  s   | S rK   r   rN   r   r   r   	__enter__  s    zParser.__enter__c                 G  s   |    d S rK   )rF   rG   r(   r   r   r   __exit__  s    zParser.__exit__c              	   C  s   | j r.| d d | _| _ | js.d}t|| js@d}t|| jr|t| j$}zt	
|| _W 5 | j  X W 5 Q R X | jS )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.
        rY   Nzimage was incompletezcannot parse this image)r   r   r   r   r   r   r   r   r`   r   r8   )rG   r   r9   r   r   r   rF     s    

zParser.close)r)   r*   r+   r   incrementalr   r,   r   r   r'   r   r   r   r   r   rF   r   r   r   r   r   |  s   
Lr   None)returnc              
   C  s   |    t| dsd| _|jtd tt|| jd d }z$| }|	  t
| |||| W n: ttjfk
r } zt
| |||d| W 5 d}~X Y nX t|dr|	  dS )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   rW   r      Nflush)r`   rc   r   ro   r"   maxr6   rD   rk   r   _encode_tiler   r   UnsupportedOperation)rl   r9   r3   bufsizefhexcr   r   r   _save  s    	
$
r   zlist[_Tile]r^   c              	   C  s   |D ]\}}}}	|dkr"| | t| j||	| j}
z|
| j| |
jrd|
	| |

 d }n:|r|
|dd  \}}|| |rhqqhn|
||}|dk rt|dd|W 5 |
  X qd S )Nr   r   Tr   )rh   r   Z_getencoderrC   r   rs   rt   rl   	pushes_fdrv   encode_to_pyfdencodewriteencode_to_filer   )rl   r9   r3   r   r   r   Zencoder_namer%   r'   r(   r   errcoder   r   r   r   r   !  s$    


r   c                 C  s   |dkrdS |t kr:| |}t||k r6d}t||S g }|}|dkrx| t|t }|s`qx|| |t|8 }qBtdd |D |k rd}t|d|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   rY   zTruncated File Readc                 s  s   | ]}t |V  qd S rK   )rb   )r[   r   r   r   r   	<genexpr>Y  s     z_safe_read.<locals>.<genexpr>)	SAFEBLOCKrf   rb   r   r   appendsumjoin)r9   rD   r   r   Zremaining_sizeblockr   r   r   
_safe_read<  s(    

r   c                   @  s   e Zd Zdd Zdd ZdS )PyCodecStatec                 C  s   d| _ d| _d| _d| _d S )Nr   )xsizeysizexoffyoffrN   r   r   r   r0   `  s    zPyCodecState.__init__c                 C  s    | j | j| j | j | j| j fS rK   )r   r   r   r   rN   r   r   r   r%   f  s    zPyCodecState.extentsN)r)   r*   r+   r0   r%   r   r   r   r   r   _  s   r   c                   @  s@   e Zd ZU ded< dd Zdd Zdd Zd	d
 ZdddZdS )PyCodeczIO[bytes] | Nonefdc                 G  s(   d | _ t | _d | _|| _| | d S rK   )rl   r   rQ   r   rC   init)rG   rC   r(   r   r   r   r0   m  s
    zPyCodec.__init__c                 C  s
   || _ dS )z
        Override to perform codec specific initialization

        :param args: Array of args items from the tile entry
        :returns: None
        N)r(   r   r   r   r   r   t  s    zPyCodec.initc                 C  s   dS )zT
        Override to perform codec specific cleanup

        :returns: None
        Nr   rN   r   r   r   rs   }  s    zPyCodec.cleanupc                 C  s
   || _ dS )z
        Called from ImageFile to set the Python file-like object

        :param fd: A Python file-like object
        :returns: None
        N)r   )rG   r   r   r   r   rv     s    zPyCodec.setfdNc                 C  s   || _ |r|\}}}}nd\}}}}|dkrJ|dkrJ| j j\| j_| j_n(|| j_|| j_|| | j_|| | j_| jjdks| jjdkrd}t|| jj| jj | j jd ks| jj| jj | j jd krd}t|dS )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)rl   rD   rQ   r   r   r   r   
ValueError)rG   rl   r%   Zx0Zy0x1y1r   r   r   r   rt     s&    zPyCodec.setimage)N)	r)   r*   r+   r,   r0   r   rs   rv   rt   r   r   r   r   r   j  s   
		r   c                   @  s:   e Zd ZdZdZedd Zdd Zddd	d
ddZdS )	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                 C  s   | j S rK   )	_pulls_fdrN   r   r   r   ru     s    zPyDecoder.pulls_fdc                 C  s   d}t |dS )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 decoderNr   )rG   bufferr   r   r   r   rw     s    	zPyDecoder.decodeNbytesr   )r   r   c                 C  sl   |s
| j }t| j d|}|| j| j  ||}|d dkrPd}t||d dkrhd}t|dS )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
        rT   r   znot enough image datar   zcannot decode image dataN)	rC   r   rr   rt   rl   rQ   r%   rw   r   )rG   r   rawmoder   r|   r   r   r   r   
set_as_raw  s    

zPyDecoder.set_as_raw)N)	r)   r*   r+   r   r   propertyru   rw   r   r   r   r   r   r     s   
r   c                   @  s8   e Zd ZdZdZedd Zdd Zdd Zd	d
 Z	dS )	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                 C  s   | j S rK   )
_pushes_fdrN   r   r   r   r     s    zPyEncoder.pushes_fdc                 C  s   d}t |dS )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 encoderNr   )rG   r   r   r   r   r   r     s    	zPyEncoder.encodec                 C  s2   | j s
dS | d\}}}|r*| 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   )rG   Zbytes_consumedr   r   r   r   r   r      s    zPyEncoder.encode_to_pyfdc                 C  s<   d}|dkr8|  |\}}}|dkr|||d  q|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   )rG   r   r   r   statusbufr   r   r   r     s    	zPyEncoder.encode_to_fileN)
r)   r*   r+   r   r   r   r   r   r   r   r   r   r   r   r     s   
r   )r   )N)"
__future__r   r   rp   rA   rd   typingr   r   r    r   Z
_deprecater   Z_utilr	   r6   r   rx   r   r   r   r"   r#   r-   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>   sB   
 v 
#J2