a
    ֶa`                     @   sn  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mZm	Z	 ddl
mZ ddl
mZ ddl
mZ dd ZG d	d
 d
ejZddddZd6ddZdd Zdd Zdd Zdd Zd7ddZdd Zdd Zdd  ZdZd!d" Zd#d$ Zd%d& Zd'd( Z d)d* Z!d+d, Z"d-d. Z#d8d/d0Z$d9d2d3Z%e&ej'ee e(ej'e e)ej'e e*ej'd4 e+ej'd5 dS ):    N   )Image
ImageChops	ImageFileImagePaletteImageSequence)i16le)o8)o16lec                 C   s   | d d dv S )N   )s   GIF87as   GIF89a )prefixr   r   b/Users/vegardjervell/Documents/master/model/venv/lib/python3.9/site-packages/PIL/GifImagePlugin.py_accept)   s    r   c                       s|   e Zd ZdZdZdZdZdd Zdd Ze	d	d
 Z
e	dd Zdd Zdd Z fddZdd Zdd Zdd Z  ZS )GifImageFileZGIFzCompuserve GIFFNc                 C   s,   | j d}|r(|d r(| j |d S d S )Nr   r   )fpread)selfsr   r   r   data:   s    zGifImageFile.datac                 C   s  | j d}t|std|d d | jd< t|dt|df| _g | _|d }|d@ d }|d	@ r|d
 | jd< | j d|> }tdt	|dD ]X}|d ||   kr||d    kr||d  ksn t
d|}| | _| _ qq| j | _| j  | _d | _d | _| d d S )N   znot a GIF filer   version   
      r         
background   r      RGB)r   r   r   SyntaxErrorinfoi16_sizetilerangelenr   rawglobal_palettepalette_GifImageFile__fptell_GifImageFile__rewind	_n_frames_is_animated_seek)r   r   flagsbitspir   r   r   _open@   s*    8zGifImageFile._openc                 C   s\   | j d u rV|  }z| |  d  qW n  tyJ   |  d | _ Y n0 | | | j S )Nr   )r.   r,   seekEOFErrorr   currentr   r   r   n_frames^   s    

zGifImageFile.n_framesc                 C   sh   | j d u rb| jd ur"| jdk| _ n@|  }z| d d| _ W n tyV   d| _ Y n0 | | | j S )Nr   TF)r/   r.   r,   r6   r7   r8   r   r   r   is_animatedj   s    




zGifImageFile.is_animatedc                 C   s   |  |sd S || jk r(d | _| d | j}t| jd |d D ]L}z| | W qB ty } z | | td|W Y d }~qBd }~0 0 qBd S )Nr   r   zno more images in GIF file)Z_seek_check_GifImageFile__frameimr0   r&   r7   r6   )r   frameZ
last_framefer   r   r   r6   {   s    



zGifImageFile.seekc                    s  |dkr:d| _ d | _g d| _d| _| j| j d| _n| jrH| 	  || jd krdt
d| || _g | _| j| _| j r| j| j  |  rqd| _ | jdkrd | _d| jv rd| _| j| jd d | jdtj| _| jd= nd| _| jdtj| _| jr | j| j| j d }i }d }d }| jd}|r|d	krTqq0|d
kr| jd}|  }|d dkr|d }|d@ r|d }t|dd |d< d|@ }	|	d? }	|	rx|	| _n|d dkr|r0d|v r|d  |7  < n||d< |  }qؐq0nd|d dkrx|| j f|d< |d d dkrx|  }t|dkrx|d dkrxt|d|d< |  rqxq0|dkr0| jd}t|dt|d }
}|
t|d |t|d  }}|| jd ks|| jd krt|| jd t|| jd f| _|
|||f| _|d }|d@ dk}|d@ rf|d@ d }td| jd|> }| jdd }| j | _ qn q0|p| j  fd d!}z| jdk rd | _n| jdkrD| j\}
}}}||
 || f}t | | j!d|}|d urd}||d" }nd}|| j!d#d}tj"#|||| _nh| jr`| $| j| j| _nL|d ur| j\}
}}}||
 || f}t | tj"#d|||d" | _W n t%y   Y n0 |d ur|dkr|d ur|| jd< d$|
|||f| j ||ffg| _nt&d%D ]4}||v r2|| | j|< n|| jv r| j|= q|dkr r^d&nd'| _| jd&kr|sdd(l'm'} || j}|| _(n | _)|| _*d S ))Nr   )r   r   r   r   r   zcannot seek to frame transparencyRGBAr       ;   !   r   r   duration   r      comment   	extensionr      NETSCAPE2.0loop   ,	      r   r   @   r   r   c                    s2    r$t  j| d | d d  } n
| | | f} | S )Nr   )tupler*   )colorZframe_paletter   r   _rgb  s     
z GifImageFile._seek.<locals>._rgb)r   r   gif)rG   rJ   rL   rN   PL)copy)+Z_GifImageFile__offsetZdisposedispose_extentr<   r+   r6   r-   Zdisposal_methodr%   load
ValueErrorr   r   Zpyaccessr"   moder=   putpalettealphaconvertr   ZFLOYDSTEINBERGpaster   r#   r,   r'   sizemaxr$   r   r(   r)   Z_decompression_bomb_checkgetcorefill_cropAttributeErrorr7   rZ   r*   _frame_palette_frame_transparency)r   r>   r*   r"   Zframe_transparency	interlacer   blockr1   Zdispose_bitsZx0Zy0x1y1r2   rV   Zdispose_sizerT   Zdispose_modekrZ   r   rU   r   r0      s   







 "












zGifImageFile._seekc                    s   | j dkr2d| jv rtj| j| j| jd | _nT| j| _| j	rzd| _tjd| j| j
pZd| _| jj| j	   d | _	nd| _d | _t   d S )Nr   rB   rX   rY   )r<   r"   r   re   rf   r^   rb   r=   _prev_imri   rj   
putpalettegetdatasuperload_preparer   	__class__r   r   rt   \  s    

zGifImageFile.load_preparec                 C   s   | j dkrd S | jd ur6| j| jd | jd}n| jd}| || j}| j| _| jj| _|jdkr| j	|| j| n| j	|| j d S )Nr   rC   r    )
r<   rj   r=   r_   r`   rg   r[   rp   r^   ra   )r   Zframe_imr   r   r   load_endo  s    



zGifImageFile.load_endc                 C   s   | j S N)r<   ru   r   r   r   r,     s    zGifImageFile.tellc                 C   sF   z8z| j | jkr| j   W n ty.   Y n0 W d | _ nd | _ 0 d S ry   )r+   r   closerh   ru   r   r   r   
_close__fp  s    zGifImageFile._close__fp)__name__
__module____qualname__formatformat_descriptionZ!_close_exclusive_fp_after_loadingr)   r   r5   propertyr:   r;   r6   r0   rt   rx   r,   r{   __classcell__r   r   rv   r   r   2   s"   

 Sr   rY   rX   )1rY   rX   Fc                 C   s   | j tv r|   | S t| j dkr|rd}| jrJt| j d d }| jdtj	|d} | jj dkr| jj
 D ]&}|d dkrt| jj
| | jd	<  qqt| S | dS | d
S )a  
    Takes an image (or frame), returns an image in a mode that is appropriate
    for saving in a Gif.

    It may return the original image, or it may return an image converted to
    palette or 'L' mode.

    UNDONE: What is the point of mucking with the initial call palette, for
    an image that shouldn't have a palette, or it would be a mode 'P' and
    get returned in the RAWMODE clause.

    :param im: Image object
    :param initial_call: Default false, set to true for a single frame.
    :returns: Image object
    r       r   r   rX   )r*   colorsrC   r   rB   rY   )r^   RAWMODEr\   r   Zgetmodebaser*   r'   rr   r`   ZADAPTIVEr   keysr"   )r=   Zinitial_callZpalette_sizeZrgbar   r   r   _normalize_mode  s"    

r   c           	   	   C   sn  d}|r>t |tttfr(t|dd }t |tjr>t|j}| jdkrb|s| jddd }n*|s|tdd t	dD }tjd|d| _|rBg }t	dt
|d	D ]J}t|||d	  }z| jj| }W n ty   d}Y n0 || qt|D ]:\}}|du rt	t
|D ]}||vr|||<  qqq| |} n t| |}|durb| ||S || j_| S )
at  
    Normalizes the palette for image.
      - Sets the palette to the incoming palette, if provided.
      - Ensures that there's a palette for L mode images
      - Optimizes the palette if necessary/desired.

    :param im: Image object
    :param palette: bytes object containing the source palette, or ....
    :param info: encoderinfo
    :returns: Image object
    Ni   rX   r    c                 s   s   | ]}|d  V  qdS )r   Nr   ).0r4   r   r   r   	<genexpr>      z%_normalize_palette.<locals>.<genexpr>r*   r   r   )
isinstancebytes	bytearraylistr   r*   r^   r=   Z
getpaletter&   r'   rS   r   KeyErrorappend	enumerateZremap_palette_get_optimize)	r=   r*   r"   Zsource_paletteused_palette_colorsr4   Zsource_colorindexjr   r   r   _normalize_palette  sB    






r   c              	   C   s   t | d}|j D ]\}}| j|| qt||| j}t|| jD ]}|| qFd}t| rj|dB }t	|| d| dt| f|_
t||dd| j dt|j fg |d d S )NTr   rR   r   r   r   rW       )r   r"   itemsencoderinfo
setdefaultr   _get_global_headerwriteget_interlace_write_local_headerZencoderconfigr   _saverb   r   r^   )r=   r   r*   Zim_outro   vr   r1   r   r   r   _write_single_frame  s    
$r   c              	   C   s  | j d| jd}| j d| jd}g }d}d }t| g| j dg D ]}t|D ]}	t|	 }	|dkr|	j	 D ]\}
}| j 
|
| qt|	|| j }	| j  }t|ttfr|| |d< t|ttfr|| |d< |d7 }|r|d }|ddkrd|d u r^| j d| jdd	}t|	|}td
|	j|}||d d j |}n|d }t|	t|krt|	|}nt|	d|d}| }|s|r`|d d  |d 7  < q`nd }||	||d q`qPt|dkr|D ]}|d }	|d s:t|	|d D ]}|| q"d}n0|sLd|d d< |	|d }	|d d d }t||	||d  qdS d| j v rt| j d ttfrt | j d | j d< d S )NrG   disposalr   Zappend_imagesr   rA   r   rB   )r   r   r   rX   r=   r    r   )r=   bboxr   r   r   Tinclude_color_table)!r   rd   r"   	itertoolschainr   Iteratorr   rZ   r   r   r   r   r   rS   _get_backgroundr   newrb   rq   r*   _get_palette_bytesr   Zsubtract_modulor`   Zgetbboxr   r'   r   r   Zcrop_write_frame_datasum)r=   r   r*   rG   r   Z	im_framesZframe_countZbackground_imZ
imSequenceim_framero   r   r   previousrT   r   Zbase_imdeltar   Z
frame_datar   offsetr   r   r   _write_multiple_frames  sv    



r   c                 C   s   t | ||dd d S )NT)save_all)r   )r=   r   filenamer   r   r   	_save_allP  s    r   c                 C   s   d| j v sd| jv r,| j d| jd}nd }| j dd| j d< |rTt| ||s`t| || |d t|dr||  d S )Nr*   optimizeTrD   flush)r   r"   rd   r   r   r   hasattrr   )r=   r   r   r   r*   r   r   r   r   T  s    

r   c                 C   s$   | j dd}t| jdk r d}|S )Nrk   r      r   )r   rd   minrb   )r=   rk   r   r   r   r   e  s    r   c                 C   s  d}z|j d }W n ty$   Y nH0 t|}d}t||j }|d urlz||}W n tyj   d}Y n0 d|j v rt|j d d }nd}t|j dd}|s|dks|r|rdnd}	|	|d	> O }	|sd}| d
td td t|	 t	| t| td  d|j v rdt
|j d kr| d
td  |j d }
t|
tr\|
 }
tdt
|
dD ],}|
||d  }| tt
||  ql| td d|j v r|j d }| d
td td d td td t	| td  |j d}|r4t|}t|}|r4|dB }||B }| dt	|d  t	|d  t	|jd  t	|jd  t|  |r|r| t| | td d S )NFrB   TrG   r   r   r   r   r   rE   rF   rQ   rJ   rI   rK   rN   r   rM   r   r   r   rO   r   )r   r   intr   r   r]   rd   r   r	   o16r'   r   strencoder&   r   _get_color_table_sizerb   _get_header_palette)r   r=   r   r1   Ztransparent_color_existsrB   r   rG   r   Zpacked_flagrJ   r4   ZsubblockZnumber_of_loopsr   palette_bytescolor_table_sizer   r   r   r   o  s    


 




r   c           
      C   s  |   }zt|d}| jdkr8tjd|g|tjd ntdd|g}dg}tj|tjtjd}tj||j|tjd}|j	  |
 }	|	rt|	||
 }	|	rt|	|W d    n1 s0    Y  W zt| W n ty   Y n0 n&zt| W n ty   Y n0 0 d S )Nwbr    Zppmtogif)stdoutstderrZppmquantZ256)stdinr   r   )_dumpopenr^   
subprocess
check_callDEVNULLPopenPIPEr   rz   waitCalledProcessErrorosunlinkOSError)
r=   r   r   tempfiler?   Z	quant_cmdZ	togif_cmdZ
quant_procZ
togif_procretcoder   r   r   _save_netpbm  sB    



,r   c                 C   s   | j dv r|r|ddrtp&| j dk}|s<| j| j dk rg }t|  D ]\}}|rL|| qL|st|dkrt	|t|kr|S dS )aL  
    Palette optimization is a potentially expensive operation.

    This function determines if the palette should be optimized using
    some heuristics, then returns the list of palette entries in use.

    :param im: Image object
    :param info: encoderinfo
    :returns: list of indexes of palette entries in use, or None
    )rX   rY   r   r   rY   i   r   N)
r^   rd   _FORCE_OPTIMIZEwidthheightr   Z	histogramr   r'   rc   )r=   r"   Zoptimiser   r4   countr   r   r   r     s    
r   c                 C   s:   | sdS t | dk rdS ttt | d dd S d S )Nr   rP   r   r   r   )r'   mathceillog)r   r   r   r   r     s
    r   c                 C   s<   t | }d|> t| d  }|dkr8| tdd | 7 } | S )z
    Returns the palette, null padded to the next power of 2 (*3) bytes
    suitable for direct inclusion in the GIF header

    :param palette_bytes: Unpadded palette bytes, in RGBRGB form
    :returns: Null padded palette
    r   r   r   )r   r'   r	   )r   r   Zactual_target_size_diffr   r   r   r   '  s
    r   c                 C   s   | j j S )z
    Gets the palette for inclusion in the gif header

    :param im: Image object
    :returns: Bytes, len<=768 suitable for inclusion in gif header
    r   )r=   r   r   r   r   9  s    r   c              
   C   sn   d}|rj|}t |trjz| j|| }W n@ tyh } z(t|dkrRW Y d }~dS  W Y d }~n
d }~0 0 |S )Nr   z$cannot allocate more than 256 colors)r   rS   r*   Zgetcolorr]   r   )r=   ZinfoBackgroundr   r@   r   r   r   r   C  s    
r   c                 C   s   d}dD ]T}|r||v r|dkr,|| dks|dkrTdt ||   krPdksTq qd} qrq| jd	dkrrd}t| |d
}t| }t|}d| t| jd  t| jd  t|d t|td t	|gS )z2Return a list of strings representing a GIF headers   87a)rB   rG   rN   rJ   rG   r   rJ   r   rK   s   89ar   r   s   GIFr   )
r'   r"   rd   r   r   r   r   rb   r	   r   )r=   r"   r   ZextensionKeyr   r   r   r   r   r   r   W  s:    
r   c              	   C   sV   zJ||_ t| ||d t|| dd|j dt|j fg | d W |` n|` 0 d S )Nr   rW   r   r   )r   r   r   r   rb   r   r^   r   )r   r   r   paramsr   r   r   r   ~  s    r   c                 C   sd   t | |}|du ri }d|vr6d| jv r6| jd |d< t| ||}|j| _|j| _t| |}||fS )a  
    Legacy Method to get Gif data from image.

    Warning:: May modify image data.

    :param im: Image object
    :param palette: bytes object containing the source palette, or ....
    :param info: encoderinfo
    :returns: tuple of(list of header items, optimized palette)

    Nr   )r   r"   r   r*   r=   r   )r=   r*   r"   r   Zim_modheaderr   r   r   	getheader  s    

r   r   c                 K   s0   G dd d}|    | }t|| || |jS )a  
    Legacy Method

    Return a list of strings representing this image.
    The first string is a local image header, the rest contains
    encoded image data.

    :param im: Image object
    :param offset: Tuple of (x, y) pixels. Defaults to (0,0)
    :param \**params: E.g. duration or other encoder info parameters
    :returns: List of Bytes containing gif encoded frame data

    c                   @   s   e Zd Zg Zdd ZdS )zgetdata.<locals>.Collectorc                 S   s   | j | d S ry   )r   r   )r   r   r   r   r   r     s    z getdata.<locals>.Collector.writeN)r|   r}   r~   r   r   r   r   r   r   	Collector  s   r   )r\   r   r   )r=   r   r   r   r   r   r   r   rr     s
    rr   z.gifz	image/gif)F)F)NN)r   ),r   r   r   r    r   r   r   r   r   _binaryr   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   rr   Zregister_openr   Zregister_saveZregister_save_allZregister_extensionZregister_mimer   r   r   r   <module>   sH   	  a
$5N

T2%

'

!