
    Ng}              	         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 dd
lmZmZ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lm Z m!Z!m"Z"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.  ed          Z/e0e1e1e1e1e1e1f         Z2e0e1e1f         Z3e0e1e1e1e1e1e1e1e1f         Z4ee2e3e4f         Z5 G d de6          Z7 G d de6          Z8 G d de8          Z9 G d de6          Z:d6dZ;d7d!Z<d8d*Z= G d+ d,e          Z> G d- d.e          Z? G d/ d0e?          Z@ G d1 d2e@          ZA G d3 d4e?          ZBd5S )9zExtract images embedded in PDF.    )annotations)ABCabstractmethod)copy)Decimal)BytesIO)zip_longest)Path)copyfileobj)AnyBinaryIOCallable
NamedTupleTypeVarUnioncast)Image)ImageCmsProfile)jbig2)BufferPdfPdfErrorStreamDecodeLevel)DependencyError)_transcoding)Array
DictionaryNameObjectStreamStringTc                      e Zd ZdZdS )UnsupportedImageTypeErrorz<This image is formatted in a way pikepdf does not supported.N__name__
__module____qualname____doc__     P/var/www/html/ai-engine/env/lib/python3.11/site-packages/pikepdf/models/image.pyr$   r$   )   s        FFFFr+   r$   c                      e Zd ZdZdS )NotExtractableErrorz5Indicates that an image cannot be directly extracted.Nr%   r*   r+   r,   r.   r.   -   s        ????r+   r.   c                      e Zd ZdZdS )"HifiPrintImageNotTranscodableErrorzJImage contains high fidelity printing information and cannot be extracted.Nr%   r*   r+   r,   r0   r0   1   s        TTTTr+   r0   c                      e Zd ZdZdS )InvalidPdfImageErrorz?This image is not valid according to the PDF 1.7 specification.Nr%   r*   r+   r,   r2   r2   5   s        IIIIr+   r2   valueObject | str | listc                \      fd            }t          |t                    s|g}|S )zLSimplify pikepdf objects to array of str. Keep streams, dictionaries intact.c                h   t          | t          t          f          rfd| D             S t          | t          t          t
          t          f          r| S t          | t          t          f          rt          |           S t          | t                    rt          |           S t                    )Nc                &    g | ]} |          S r*   r*   ).0subitem_converts     r,   
<listcomp>z0_array_str.<locals>._convert.<locals>.<listcomp>>   s#    :::'HHW%%:::r+   )
isinstancelistr   r    r   bytesintr   strr!   NotImplementedError)itemr:   r3   s    r,   r:   z_array_str.<locals>._convert<   s    dT5M** 	;::::T::::dVZ<== 	KdT3K(( 	t99dV%% 	;;!%(((r+   )r<   r=   )r3   resultr:   s   ` @r,   
_array_strrD   9   sO    	) 	) 	) 	) 	) 	) Xe__Ffd## Mr+   *list[Object] | Dictionary | Array | Objectreturnlist[Object]c                    t          | t                    r| S t          |                                                                           S )zEnsure value is a list of pikepdf.Object, if it was not already.

    To support DecodeParms which can be present as either an array of dicts or a single
    dict. It's easier to convert to an array of one dict.
    )r<   r=   wrap_in_arrayas_list)r3   s    r,   _ensure_listrK   M   sA     % ##%%--//000r+   objDictionary | Streamnamer@   type_Callable[[Any], T]defaultT | Nonec                    t          | ||          }	  ||          S # t          $ r |Y dS Y nw xY wt          d|z             )z@Retrieve metadata from a dictionary or stream and wrangle types.NzMetadata access for )getattr	TypeErrorrA   )rL   rN   rO   rQ   vals        r,   _metadata_from_objrW   X   sl     #tW
%
%CuSzz   ;44 ; 4t;
<
<<s   
 00c                  (    e Zd ZU dZded<   ded<   dS )PaletteDataa5  Returns the color space and binary representation of the palette.

    ``base_colorspace`` is typically ``"RGB"`` or ``"L"`` (for grayscale).

    ``palette`` is typically 256 or 256*3=768 bytes, for grayscale and RGB color
    respectively, with each unit/triplet being the grayscale/RGB triplet values.
    r@   base_colorspacer>   paletteN)r&   r'   r(   r)   __annotations__r*   r+   r,   rY   rY   e   s1           NNNNNr+   rY   c                  ,   e Zd ZdZh dZeh dz  ZddhZed/d            Ze	d0d            Z
e	d0d            Ze	d1d            Ze	d2d            Ze	d             Ze	d             Ze	d3d            Ze	d             Ze	d4d            Ze	d0d            Ze	ed5d                        Ze	d1d            Zd  Ze	d1d!            Ze	d1d"            Ze	d6d$            Zd% Ze	d7d&            Ze	d'             Ze	d8d)            Zed9d+            Zd:d-Zd.S );PdfImageBasezAbstract base class for images.>   /CalRGB/CalGray
/DeviceRGB/DeviceGray>   /CalCMYK	/ICCBased/DeviceCMYK/Separation/DeviceNrN   r@   rO   rP   rQ   r"   rF   c                    dS )z!Get metadata for this image type.Nr*   selfrN   rO   rQ   s       r,   	_metadatazPdfImageBase._metadatay         r+   r?   c                :    |                      dt          d          S )z"Width of the image data in pixels.Widthr   rk   r?   rj   s    r,   widthzPdfImageBase.width}   s     ~~gsA...r+   c                :    |                      dt          d          S )z#Height of the image data in pixels.Heightr   ro   rp   s    r,   heightzPdfImageBase.height   s     ~~hQ///r+   boolc                :    |                      dt          d          S )z)Return ``True`` if this is an image mask.	ImageMaskF)rk   ru   rp   s    r,   
image_maskzPdfImageBase.image_mask   s     ~~k4777r+   
int | Nonec                :    |                      dt          d          S )z.Bits per component for this image (low-level).BitsPerComponentr   ro   rp   s    r,   _bpczPdfImageBase._bpc   s     ~~0#q999r+   c                :    |                      dt          g           S )zColorspace (low-level).
ColorSpacerk   rD   rp   s    r,   _colorspaceszPdfImageBase._colorspaces   s     ~~lJ;;;r+   c                :    |                      dt          g           S )zBList of names of the filters that we applied to encode this image.Filterr   rp   s    r,   filterszPdfImageBase.filters   s     ~~h
B777r+   DecodeArrayc                   |                      dt          g           }|r=t          |          dv r,t          t          t          d |D                                 S | j        dv rdS | j        dk    rdS | j        dk    rd	S | j        d
k    r4|                                 dk    rdS |                                 dk    rdS t          dt          |           z             )zExtract the /Decode array.Decode)         c              3  4   K   | ]}t          |          V  d S N)float)r8   r3   s     r,   	<genexpr>z-PdfImageBase._decode_array.<locals>.<genexpr>   s(      *L*LE5<<*L*L*L*L*L*Lr+   rb   r`   )              ?ra   r_   )r   r   r   r   r   r   re   )r   r   r   r   r   r   r   r   rd   LRGBz5Don't how to retrieve default /Decode array for image)
rk   rK   lenr   r   tuple
colorspace_approx_mode_from_iccrA   repr)rj   decodes     r,   _decode_arrayzPdfImageBase._decode_array   s     ~~hbAA 	Nc&kkY..U*L*LV*L*L*L%L%LMMM?999:?77711?m++;;?k))))++s22!z))++u4455!Cd4jjP
 
 	
r+   c                :    |                      dt          g           S )z/List of the /DecodeParms, arguments to filters.DecodeParms)rk   rK   rp   s    r,   decode_parmszPdfImageBase.decode_parms   s     ~~m\2>>>r+   
str | Nonec                   | j         rdS | j        r| j        d         | j        v r| j        d         S | j        d         dk    rT| j        d         }t          |t                    r|| j        v r|S t          |t
                    r|d         dv r|d         S | j        d         dk    rdS t          dt          | j                  z             )z:PDF name of the colorspace that best describes this image.Nr   /Indexed   )rd   rg   r`   r_   rg   z not sure how to get colorspace: )rx   r   MAIN_COLORSPACESr<   r@   r=   rA   r   )rj   subspaces     r,   r   zPdfImageBase.colorspace   s     ? 	4 	" #t'<<<(++ #z11,Q/h,, $T=R1R1R#Oh-- '(1+ B 3 3 $A;& #z11!z!.d6G1H1HH
 
 	
r+   c                J    | j         | j         dk    r| j        rdndS | j         S )z!Bits per component of this image.Nr   r   r   )r|   rx   rp   s    r,   bits_per_componentzPdfImageBase.bits_per_component   s/     9	Q.11Q.yr+   ImageCmsProfile | Nonec                    dS )z4Return ICC profile for this image if one is defined.Nr*   rp   s    r,   icczPdfImageBase.icc   rl   r+   c                    d| j         v S )z/Check if the image has a defined color palette.r   )r   rp   s    r,   indexedzPdfImageBase.indexed   s     T...r+   c                    	 | j         }|d         dk    r|d         d         |k    rdS |d         |k    rdS n# t          t          t          f$ r Y nw xY wdS )Nr   r   r   TF)r   
IndexErrorAttributeErrorKeyError)rj   rN   css      r,   _colorspace_has_namez!PdfImageBase._colorspace_has_name   sx    	"B!u
""r!uQx4'7'7t!u}}t NH5 	 	 	D	us   %8 8 AAc                ,    |                      d          S )<Check if image has a /DeviceN (complex printing) colorspace.rg   r   rp   s    r,   is_device_nzPdfImageBase.is_device_n   s     ((444r+   c                ,    |                      d          S )r   rf   r   rp   s    r,   is_separationzPdfImageBase.is_separation   s     ((777r+   tuple[int, int]c                    | j         | j        fS )z!Size of image as (width, height).)rq   rt   rp   s    r,   sizezPdfImageBase.size   s     z4;&&r+   c                    | j         r| j        d         d         }n| j        d         }t          |d                   }|dk    rdS ddd}| j        j        j        }|                    |d          S )Nr   z/Nr   r   CMYK)zRGB r    )r   r   r?   r   profilexcolor_spaceget)rj   icc_profileicc_profile_nchannelsmode_from_xcolor_spacer   s        r,   r   z"PdfImageBase._approx_mode_from_icc   s    < 	/+A.q1KK+A.K #K$5 6 6 A%%3 +0!@!@x'4%)),;;;r+   c                   d}| j         rd}n| j        rd}n| j        rd}n| j        dk    r| j        dk    rd}n| j        dk    r| j        dk    rd}nf| j        d	k    rd
}nX| j        dk    rd}nJ| j        dk    r?	 |                                 }n)# t          t          f$ r}t          d          |d}~ww xY w|dk    rt          d          d|S )z``PIL.Image.mode`` equivalent for this image, where possible.

        If an ICC profile is attached to the image, we still attempt to resolve a Pillow
        mode.
        r   DeviceN
SeparationPrb   r   1r   ra   r   re   r   rd   z-Not sure how to handle PDF image of this typeN)	r   r   r   r   r   r   
ValueErrorrU   rA   )rj   mes      r,   modezPdfImageBase.mode  s3     	AA 	AA\ 	AA_--$2IQ2N2NAA_--$2IA2M2MAA_,,AA_--AA_++..00	*   )C  77%?  s   ;B B6!B11B6c                T    t          t          | j        | j        i                     S )a  Return normalized the Filter and DecodeParms data.

        PDF has a lot of possible data structures concerning /Filter and
        /DecodeParms. /Filter can be absent or a name or an array, /DecodeParms
        can be absent or a dictionary (if /Filter is a name) or an array (if
        /Filter is an array). When both are arrays the lengths match.

        Normalize this into:
        [(/FilterName, {/DecodeParmName: Value, ...}), ...]

        The order of /Filter matters as indicates the encoding/decoding sequence.
        )	fillvalue)r=   r	   r   r   rp   s    r,   filter_decodeparmszPdfImageBase.filter_decodeparms.  s&     Kd.?2NNNOOOr+   PaletteData | Nonec                D   | j         sdS 	 | j        \  }}}}n"# t          $ r}t          d          |d}~ww xY w| j        s#| j        s| j        st          |t                    rt          |d                   }nt          |          }t          |          }|| j
        vr|| j        vrt          d|           |dv rd}nO|dv rd}nH|d	k    rd
}n?|dk    rd}n6|dk    rd}n-|dk    r|                                 }nt          d|           t          ||          S )z8Retrieve the color palette for this image if applicable.Nz&Not sure how to interpret this paletter   z(not sure how to interpret this palette: r   r   r   r   re   r   rg   r   rf   r   rd   )r   r   r   r   r   r   r<   r=   r@   r>   r   PRINT_COLORSPACESrA   r   rY   )rj   _idxbase_hivallookupr   s         r,   r[   zPdfImageBase.palette>  s    | 	4	N)-):&D$ 	N 	N 	NEFFAM	N8 	t' 	4+= 	DRVAWAW 	tAw<<DDt99Dvt,,,T=S1S1S%&WQU&W&WXXX,,,DD000DD]""DDZDD]""DD[  --//DD%&WQU&W&WXXX4(((s    
727Image.Imagec                    dS )z6Convert this PDF image to a Python PIL (Pillow) image.Nr*   rp   s    r,   as_pil_imagezPdfImageBase.as_pil_image^  rl   r+   r>   c                    t                      }|                                 5 }|                    |d           |                                cddd           S # 1 swxY w Y   dS )z!Display hook for IPython/Jupyter.PNGN)r   r   savegetvalue)rj   bims      r,   
_repr_png_zPdfImageBase._repr_png_b  s    II   	 BGGAu::<<	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	 s   *AA!AN)rN   r@   rO   rP   rQ   r"   rF   r"   rF   r?   rF   ru   )rF   ry   )rF   r   )rF   r   rF   r   )rF   r   )rF   r@   )rF   r   rF   r   rF   r>   ) r&   r'   r(   r)   SIMPLE_COLORSPACESr   r   r   rk   propertyrq   rt   rx   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   s       ))MMM),T,T,TT&
30 0 0 ^0 / / / X/ 0 0 0 X0 8 8 8 X8 : : : X: < < X< 8 8 X8 
 
 
 X
, ? ? X? 
 
 
 X
2    X C C C ^ XC / / / X/	 	 	 5 5 5 X5 8 8 8 X8 ' ' ' X'< < <       X D P P XP ) ) ) X)> E E E ^E           r+   r^   c                  4    e Zd ZU dZded<   ded<   ded<   d2 fdZd2d	Zd
 Zed             Z	d Z
ed             Zed3d            Zd Zd4dZd5dZd5dZd5dZd5dZd6dZdddd7d!Zej        fd8d%Zej        fd9d'Zd5d(Zd:d;d,Zd- Zd<d0Zd1 Z xZS )=PdfImagea  Support class to provide a consistent API for manipulating PDF images.

    The data structure for images inside PDFs is irregular and complex,
    making it difficult to use without introducing errors for less
    typical cases. This class addresses these difficulties by providing a
    regular, Pythonic API similar in spirit (and convertible to) the Python
    Pillow imaging library.
    r    rL   r   _iccz
Pdf | None_pdf_sourcec                   	 t          |j                  }t          j        |v r&t	                                          t                    S n# t          t          f$ r Y nw xY wt	                                          t                    S )zGConstruct a PdfImage... or a PdfJpxImage if that is what we really are.)
rK   r   r   	JPXDecodesuper__new__PdfJpxImager   r   r   )clsrL   r   	__class__s      r,   r   zPdfImage.__new__x  s|    	"3:..G~((ww{333 )) 	 	 	D	 wwx(((s   AA A A c                    t          |t                    r-|j                            d          dk    rt	          d          || _        d| _        dS )zConstruct a PDF image from a Image XObject inside a PDF.

        ``pim = PdfImage(page.Resources.XObject['/ImageNN'])``

        Args:
            obj: an Image XObject
        z/Subtype/Imagez'can't construct PdfImage from non-imageN)r<   r    stream_dictr   rU   rL   r   )rj   rL   s     r,   __init__zPdfImage.__init__  sR     c6"" 	Gs':'::'F'F('R'REFFF			r+   c                Z    t          |t                    st          S | j        |j        k    S r   )r<   r^   NotImplementedrL   rj   others     r,   __eq__zPdfImage.__eq__  s)    %.. 	"!!x59$$r+   c                  |                                 }t          ||          }t          d          |_        t          d          |_        |j        dk    rt          d          |_        n|j        dv rt          d          |_        |j        dk    rdnd	|_        |j        |_	        |j
        |_        ||j        j        |<    | |          S )
a@  Insert a PIL image into a PDF (rudimentary).

        Args:
            pdf (pikepdf.Pdf): the PDF to attach the image to
            page (pikepdf.Object): the page to attach the image to
            name (str or pikepdf.Name): the name to set the image
            image (PIL.Image.Image): the image to insert
        z/XObjectr   r   ra   )r   r   rb   r   r   r   )tobytesr    r   TypeSubtyper   r~   r{   rq   rn   rt   rs   	ResourcesXObject)r   pdfpagerN   imagedataimstreams          r,   _from_pil_imagezPdfImage._from_pil_image  s     }}#t$$Z((>>:"&|"4"4HZ:%%"&}"5"5H).s):):AA!,'/t$s8}}r+   c                0    t          | j        |||          S r   rW   rL   ri   s       r,   rk   zPdfImage._metadata      !$(D%AAAr+   c                    | j         dk    rI| j        s| j        d         S t          | j        d         t                    sJ | j        d         d         S t          d          )Nrd   r   z+Don't know how to find ICC stream for image)r   r   r   r<   r=   rA   rp   s    r,   
_iccstreamzPdfImage._iccstream  sg    ?k))< ,(++d/2D99999$Q'**!"OPPPr+   rF   c                (   | j         dvrdS | j        sz| j        }|                                }t	          |          }	 t          |          | _        n:# t          $ r-}t          |          dk    rt          d          |Y d}~nd}~ww xY w| j        S )zIf an ICC profile is attached, return a Pillow object that describe it.

        Most of the information may be found in ``icc.profile``.
        )rd   r   Nzcannot open profile from stringz#ICC profile corrupt or not readable)	r   r   r  get_stream_bufferr   r   OSErrorr@   r$   )rj   	iccstream	iccbuffer
iccbytesior   s        r,   r   zPdfImage.icc  s     ?";;;4y 	I!3355I ++J+J77		   q66>>>3=  ?>>>> ys   A 
B
#BB
c                   h dfdt          | j                  D             }t          |          dk    r%t          d| j        j         d| j         d          t          |          dk    r&| j                            t          j                  g fS |d         }|dk    r | j        	                                | j        fS t          | j                  }t          d | j        d	|         D                       |_        t          | j        d	|                   |_        |                    t          j                  | j        |d	         fS )
z4Remove simple lossless compression where it appears.>   /JBIG2Decode
/DCTDecode
/JPXDecode/CCITTFaxDecodec                "    g | ]\  }}|v 	|S r*   r*   )r8   nfiltCOMPLEX_FILTERSs      r,   r;   z3PdfImage._remove_simple_filters.<locals>.<listcomp>  s'    WWWDt?V?V1?V?V?Vr+   r   zObject z has compound complex filters: z. We cannot decompress this.r   c                ,    g | ]}t          |          S r*   )r   )r8   fs     r,   r;   z3PdfImage._remove_simple_filters.<locals>.<listcomp>  s     C C CQa C C Cr+   N)	enumerater   r   rA   rL   objgen
read_bytesr   specializedread_raw_bytesr   r   r   r   r   )rj   indicesr  obj_copyr  s       @r,   _remove_simple_filterszPdfImage._remove_simple_filters  sb   
 
 
 XWWWIdl$;$;WWWw<<!%>$(/ > ><> > >   w<<18&&'8'DEErIIAJ668**,,dl::>> C C$,rr2B C C CDD$T%6rr%:;;""#4#@AA4<PQPRPRCSSSr+   streamr   r   c                   d fd}d fd}                                  \  }}|dgk    rh j        dk    r j                                        }nd}|                                         ||                     |                    |           d	S |d
gk    r6 j        dk    s |            s
 |            r|                    |           dS dS )aS  Attempt to extract the image directly to a usable image file.

        If there is no way to extract the image without decompressing or
        transcoding then raise an exception. The type and format of image
        generated will vary.

        Args:
            stream: Writable file stream to write data to, e.g. an open file
        rF   ru   c                     d} | }j         d         d         'j         d         d                             d|           }j        dk    o|| k    S )Nr   r   /ColorTransformr   r   r   r   )DEFAULT_CT_RGBctrj   s     r,   normal_dct_rgbz0PdfImage._extract_direct.<locals>.normal_dct_rgb  sb     NB&q)!,8,Q/266%~  9%>"*>>r+   c                     d} | }j         d         d         'j         d         d                             d|           }j        dk    o|| k    S )Nr   r   r(  r   r)  )DEFAULT_CT_CMYKr+  rj   s     r,   normal_dct_cmykz1PdfImage._extract_direct.<locals>.normal_dct_cmyk  sb      O B&q)!,8,Q/266%  9&@2+@@r+   r  rd   N)r   z.tifr  r   z.jpgr   )r$  r   r  r  write_generate_ccitt_headerr   )rj   r%  r,  r/  r  r   r   s   `      r,   _extract_directzPdfImage._extract_direct  s   	? 	? 	? 	? 	? 	?		A 		A 		A 		A 		A 		A 3355g()))+--o0022LL44Ts4CCDDDLL6|n$$I 0 0OO4E4ELL6tr+   r   c                   d}| j         dk    rdnd}| j        dv r7t          j        |                                 | j        | j        |          \  }}nB| j        dk    r(t          t          |                                           }nt          d          | j         dk    r/| j
        (| j
        \  }}t          j        || j        |||          }nt          j        || j        |          }|S )zAExtract an image when there are 1/2/4/8 bits packed in byte data.r   r   r   )r      r   z*BitsPerComponent must be 1, 2, 4, 8, or 16r   )r   r   r   unpack_subbyte_pixelsr  r   r   
memoryviewr  r2   r[   image_from_buffer_and_paletteimage_from_byte_buffer)rj   stridescalebuffer	base_moder[   r   s          r,   _extract_transcoded_1248bitsz%PdfImage._extract_transcoded_1248bits%  s    Y#%%1"f,,)?!!49d.Eu NFFF $))*d&<&<&>&>??FF&'STTT9 8!%Iw;	 BB 4VTYOOB	r+   c                   | j         s| j        dv rt          d          	 |                                 }n`# t          t
          f$ rL}dt          |          v r5t          j                    	                                st          d          d  d }~ww xY wt          j        d| j        |          }| j         | j        \  }}t          j        |||          }|S )N)r   r   z$1-bit RGB and CMYK are not supportedz(read_bytes called on unfilterable streamzRjbig2dec - not installed or installed version is too old (older than version 0.15)r   )rx   r   r$   r  RuntimeErrorr   r@   r   get_decoder	availabler   r   	frombytesr   r[   r   fix_1bit_palette_image)rj   r  r   r   r<  r[   s         r,   _extract_transcoded_1bitz!PdfImage._extract_transcoded_1bit?  s     	T49#?#?+,RSSS	??$$DDh' 		 		 		:c!ffDD)++5577 E &0   		 _S$)T22<#!%Iw4RGLLB	s   6 BABBc                *    |                                  S r   )rD  rp   s    r,   _extract_transcoded_maskz!PdfImage._extract_transcoded_maskW  s    ,,...r+   c           	        | j         r|                                 S | j        dv rt                      | j        dk    r=| j        dk    r2t          j        d| j        |                                 dddd          }n| j        dk    r=| j        dk    r2t          j        d| j        | 	                                dddd          }n}| j        dk    r| 
                                }n]| j        dv r | j        dk    r|                                 }n4t          t          |           d	z   t          | j                  z             | j        d
k    r(| j        !| j                                        |j        d<   |S )N>   r   r   r   r   rawr   r   r   )r   r   z, rd   r   )rx   rF  r   r0   r   r   
frombufferr   r  r  rD  r=  r$   r   rL   r   r   r   info)rj   r   s     r,   _extract_transcodedzPdfImage._extract_transcodedZ  sy   ? 	300222911146669$"9Q">"> !ty$//"3"3UE1a BB Y&  T%<%A%A!	4#9#9#;#;UFAq BB $))..00BBY*$$)@A)E)E2244BB+DJJ,=TX,NOOO?k))dh.B%)X%5%5%7%7BGM"	r+   r@   c               l   |                      |          }|r|S d}	 |                                 }|j        dk    r3|                    |dd           	 |r|                                 dS dS |r2|                    |d	           	 |r|                                 d
S d
S nA# t
          $ r4}dt          |          v rt          t          |                     | d}~ww xY w	 |r|                                 n# |r|                                 w w xY wt          t          |                     )a  Extract the image to a stream.

        If possible, the compressed data is extracted and inserted into
        a compressed image file format without transcoding the compressed
        content. If this is not possible, the data will be decompressed
        and extracted to an appropriate format.

        Args:
            stream: Writable stream to write data to

        Returns:
            The file format extension.
        r%  Nr   tifftiff_adobe_deflate)formatcompressionz.tiffpng)rP  z.pngzcalled on unfilterable stream)	r2  rK  r   r   closer   r@   r$   r   )rj   r%  direct_extractionr   r   s        r,   _extract_to_streamzPdfImage._extract_to_streamx  s    !000?? 	%$$	))++Bw&  v;OPPP  




   u---  




   	 	 	.#a&&88/T

;;B	  


  



 (T

333s/   7B% 0B% $C> %
C#//CC##C> >DNr   r%  
fileprefixBinaryIO | NonerW  c                  t          |          t          |          k    rt          d          |r|                     |          S t                      }|                     |          }|                    d           t          t          t          |                    |z             }|                    d          5 }t          ||           ddd           n# 1 swxY w Y   t          |          S )a  Extract the image directly to a usable image file.

        If possible, the compressed data is extracted and inserted into
        a compressed image file format without transcoding the compressed
        content. If this is not possible, the data will be decompressed
        and extracted to an appropriate format.

        Because it is not known until attempted what image format will be
        extracted, users should not assume what format they are getting back.
        When saving the image to a file, use a temporary filename, and then
        rename the file to its final name based on the returned file extension.

        Images might be saved as any of .png, .jpg, or .tiff.

        Examples:
            >>> im.extract_to(stream=bytes_io)  # doctest: +SKIP
            '.png'

            >>> im.extract_to(fileprefix='/tmp/image00')  # doctest: +SKIP
            '/tmp/image00.jpg'

        Args:
            stream: Writable stream to write data to.
            fileprefix (str or Path): The path to write the extracted image to,
                without the file extension.

        Returns:
            If *fileprefix* was provided, then the fileprefix with the
            appropriate extension. If no *fileprefix*, then an extension
            indicating the file type.
        z%Cannot set both stream and fileprefixrM  r   wbN)	ru   r   rU  r   seekr
   r@   openr   )rj   r%  rW  bio	extensionfilepathtargets          r,   
extract_tozPdfImage.extract_to  s   D <<4
++++DEEE 	:**&*999ii++3+77	D,,--	9::]]4   	%FV$$$	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	%8}}s   CC#&C#decode_levelr   r>   c                8    | j                             |          S )z7Decompress this image and return it as unencoded bytes.rb  )rL   r  rj   rb  s     r,   r  zPdfImage.read_bytes  s     x"""===r+   r   c                8    | j                             |          S )z+Access this image with the buffer protocol.rd  )rL   r  re  s     r,   r  zPdfImage.get_stream_buffer  s     x))|)DDDr+   c                   t                      }|                     |          }|r)|                    d           t          j        |          S |                                 }|st          t          |                     |S )zuExtract the image as a Pillow Image, using decompression as necessary.

        Caller must close the image.
        rM  r   )r   r2  r[  r   r\  rK  r$   r   )rj   r]  rT  r   s       r,   r   zPdfImage.as_pil_image  s{    
 ii 000<< 	#HHQKKK:c??"%%'' 	8+DJJ777	r+   r  r   bytes | Nonec                &   | j         st          d          dg}|D ]?\  }}| j         d                             ||          |k    rt          d| d|           @| j         d                             dd          }d}|dk     rd}n|dk    rd	}d
}nd	}| j         d                             dd          }	| j        }
|	rd
nd}t          |
          dk    r|
dk    rd
|z
  }t          |          }|d}t          j        | j        |||||          S )z8Construct a CCITT G3 or G4 header from the PDF metadata.z$/CCITTFaxDecode without /DecodeParms)z/EncodedByteAlignFr   z&/CCITTFaxDecode with decode parameter z not equal z/KNr4     r   z	/BlackIs1Fr   )r   r   r+   )data_lengthccitt_group
t4_options
photometryr   )	r   r   r   r$   r   r   r   generate_ccitt_headerr   )rj   r  r   expected_defaultsrN   rV   krm  rl  black_is_oner   rn  img_sizes                r,   r1  zPdfImage._generate_ccitt_header  sz   
   	ECDDD )
 + 	 	ID# #''c22c99/STSScSS   :
 a $$T1--
q55KKUUKJJK(+//UCC# '-QQA
 v;;!* 4 4ZJt99;C1I #!!
 
 
 	
r+   c                R    |                                                                   dS )z$Show the image however PIL wants to.N)r   showrp   s    r,   ru  zPdfImage.show  s&      """""r+   r  r   c                    || _         d S r   )r   )rj   r  s     r,   _set_pdf_sourcezPdfImage._set_pdf_source#  s    r+   c                    	 | j         }n# t          $ r d}Y nw xY wd| d| j         d| j         dt	          t          |                      d	S )N?z<pikepdf.PdfImage image mode= size=x at >r   rA   rq   rt   hexidrj   r   s     r,   __repr__zPdfImage.__repr__&  s    	9DD" 	 	 	DDD	CD C CJC C!%C C25bhh--C C C	
   
 )rL   r    r   r%  r   rF   r   r   )r%  r   rF   r@   )r%  rX  rW  r@   rF   r@   )rb  r   rF   r>   )rb  r   rF   r   r   )r  r>   r   rh  rF   r>   )r  r   ) r&   r'   r(   r)   r\   r   r   r   classmethodr  rk   r   r  r   r$  r2  r=  rD  rF  rK  rU  ra  r   r   r  r  r   r1  ru  rw  r  __classcell__r   s   @r,   r   r   j  sU          KKK    
) 
) 
) 
) 
) 
)   % % %
   [4B B B Q Q XQ    X*T T T84 4 4 4l   4   0/ / / /   <#4 #4 #4 #4L ,02- - - - - -` 1B0M> > > > > 1B0ME E E E E   "4
 4
 4
 4
 4
l# # #   
 
 
 
 
 
 
r+   r   c                       e Zd ZdZ fdZd ZddZd fd
Ze fd            Z	edd            Z
edd            Zd Z xZS )r   zSupport class for JPEG 2000 images. Implements the same API as :class:`PdfImage`.

    If you call PdfImage(object_that_is_actually_jpeg2000_image), pikepdf will return
    this class instead, due to the check in PdfImage.__new__.
    c                |    t                                          |           |                                 | _        dS )zInitialize a JPEG 2000 image.N)r   r   r   _jpxpil)rj   rL   r   s     r,   r   zPdfJpxImage.__init__8  s2    ((**r+   c                    t          |t                    st          S | j        |j        k    o$t          |t                    o| j        |j        k    S r   )r<   r^   r   rL   r   r  r   s     r,   r   zPdfJpxImage.__eq__=  sN    %.. 	"!!H	! .5+...-	
r+   r%  r   rF   r   c               p    |                                  \  }}|dgk    rd S |                    |           dS )Nr  z.jp2)r$  r0  )rj   r%  r  r   s       r,   r2  zPdfJpxImage._extract_directF  s@    3355g|n$$4Tvr+   r   c                D    t                                                      S r   )r   rK  )rj   r   s    r,   rK  zPdfJpxImage._extract_transcodedM  s    ww**,,,r+   c                    t                      j        }|r|S | j        j        dk    rdgS | j        j        dk    rdgS t	          d          )zReturn the effective colorspace of a JPEG 2000 image.

        If the ColorSpace dictionary is present, the colorspace embedded in the
        JPEG 2000 data will be ignored, as required by the specification.
        r   rb   r   ra   zComplex JP2 colorspace)r   r   r  r   rA   )rj   super_colorspacesr   s     r,   r   zPdfJpxImage._colorspacesP  s_     "GG0 	%$$<##!?"<%% >!!":;;;r+   r?   c                    dS )z=Return 8, since bpc is not meaningful for JPEG 2000 encoding.r   r*   rp   s    r,   r|   zPdfJpxImage._bpcb  s	     qr+   ru   c                    dS )z4Return False, since JPEG 2000 should not be indexed.Fr*   rp   s    r,   r   zPdfJpxImage.indexedk  s	     ur+   c                r    d| j          d| j         d| j         dt          t	          |                      d	S )Nz)<pikepdf.PdfJpxImage JPEG2000 image mode=rz  r{  r|  r}  )r   rq   rt   r  r  rp   s    r,   r  zPdfJpxImage.__repr__s  s`    C	 C CJC C!%C C25bhh--C C C	
r+   r  r   r   r   )r&   r'   r(   r)   r   r   r2  rK  r   r   r|   r   r  r  r  s   @r,   r   r   1  s         + + + + +

 
 
   - - - - - - < < < < X<"    X    X
 
 
 
 
 
 
r+   r   c                  H   e Zd ZU dZi dddddddd	d
dddddddddddddddddddddd d!d"d#Zd$ e                                D             Zd%ed&<   d'ed(<   dCd,Zd- Z	e
d.             Zd/ ZdDd2Zed3             Zd4 ZdEd6ZdFd8Zd9d:d;dGd@ZdA ZdB Zd9S )HPdfInlineImagez$Support class for PDF inline images.s   /Ws   /Widths   /Hs   /Heights   /BPCs   /BitsPerComponents   /IMs
   /ImageMasks   /CSs   /ColorSpaces   /Fs   /Filters   /DPs   /DecodeParmss   /Gs   /DeviceGrays   /RGBs
   /DeviceRGBs   /CMYKs   /DeviceCMYKs   /Is   /Indexeds   /AHxs   /ASCIIHexDecodes   /A85s   /ASCII85Decodes   /LZWs
   /LZWDecodes   /RLs   /RunLengthDecodes   /CCFs   /CCITTFaxDecodes   /DCTs
   /DCTDecodec                    i | ]\  }}||	S r*   r*   )r8   rq  vs      r,   
<dictcomp>zPdfInlineImage.<dictcomp>  s    8881q!888r+   r   _dataztuple[Object, ...]_image_object
image_dataimage_objectr   c                   | _         | _        d                     fd|D                       }	 t          j        d|z   dz             }n8# t
          $ r+}t          d|                    d          z             |d}~ww xY w| _        dS )zConstruct wrapper for inline image.

        Args:
            image_data: data stream for image, extracted from content stream
            image_object: the metadata for image, also from content stream
            c              3  P   K   | ] }                     |j                   V  !dS )remap_namesN)_unparse_objABBREVS)r8   rL   rj   s     r,   r   z*PdfInlineImage.__init__.<locals>.<genexpr>  sI       
 
ADDct|<<
 
 
 
 
 
r+   s   << s    >>zparsing inline unicode_escapeN)r  r  joinr   parser   r   rL   )rj   r  r  reparsereparsed_objr   s   `     r,   r   zPdfInlineImage.__init__  s      
))) 
 
 
 
HT
 
 
 
 
	X!<(86(ABBLL 	X 	X 	X,w~~>N/O/OOPPVWW	Xs   A 
B&A==Bc                    t          |t                    st          S | j        |j        k    oHt          |t                    o3| j                                        |j                                        k    S r   )r<   r^   r   rL   r  r  _inline_image_raw_bytesr   s     r,   r   zPdfInlineImage.__eq__  sk    %.. 	"!!H	! 5.11 
2244;66889		
r+   c                   t          |t                    rnt          |t                    rC|                    d          }t          |t                    sJ |                    ||          S |                    d          S t          |t                    r|rdndS t          |t          t          t          f          r"t          |                              d          S t          t          |                    )NT)resolveds   trues   falseascii)r<   r   r   unparser>   r   ru   r?   r   r   r@   encoderA   r   )r   rL   r  rN   s       r,   r  zPdfInlineImage._unparse_obj  s    c6"" 	.#t$$ 3{{D{11!$....."tT222;;;---c4   	0!/77x/cC%011 	,s88??7+++!$s)),,,r+   c                0    t          | j        |||          S r   r  ri   s       r,   rk   zPdfInlineImage._metadata  r	  r+   rF   r>   c                V      fd fd}d                      |                      S )zACreate the content stream bytes that reproduce this inline image.c               3     K   j         D ]9}                     | j                  }t          |t                    sJ |V  :d S )Nr  )r  r  REVERSE_ABBREVSr<   r>   )metadata_objunparsedrj   s     r,   metadata_tokensz/PdfInlineImage.unparse.<locals>.metadata_tokens  sh       $ 2  ,, d.B -   "(E22222 r+   c               3     K   dV  d                     d               D                       V  dV  j                                        V  dV  d S )Ns   BI
r  c              3     K   | ]}|V  d S r   r*   )r8   r   s     r,   r   zFPdfInlineImage.unparse.<locals>.inline_image_tokens.<locals>.<genexpr>  s"      99!A999999r+   s   
ID
s   EI)r  r  r  )r  rj   s   r,   inline_image_tokensz3PdfInlineImage.unparse.<locals>.inline_image_tokens  so      MMM))99'8'899999999OOO*4466666KKKKKr+   r+   )r  )rj   r  r  s   ` @r,   r  zPdfInlineImage.unparse  sY    	 	 	 	 		 	 	 	 	 	 xx++--...r+   c                     t          d          )zIRaise an exception since ICC profiles are not supported on inline images.zJInline images with ICC profiles are not supported in the PDF specification)r2   rp   s    r,   r   zPdfInlineImage.icc  s     #X
 
 	
r+   c                    	 | j         }n# t          $ r d}Y nw xY wd| d| j         d| j         dt	          t          |                      d	S )Nry  z#<pikepdf.PdfInlineImage image mode=rz  r{  r|  r}  r~  r  s     r,   r  zPdfInlineImage.__repr__  s    	9DD" 	 	 	DDD	C$ C CJC C!%C C25bhh--C C C	
r  r   c                   t          j                    }|                    | j        | j        f           |j        d                             | j         d| j         d                    d          d           |j        d                             |                                            |j        d         	                                 t          t          t          d |j        d         j                                        D                                 }t          |          }|                    |           |S )	N)	page_sizer   z 0 0 z 0 0 cmr  T)prependc              3     K   | ]}|V  d S r   r*   )r8   r   s     r,   r   z6PdfInlineImage._convert_to_pdfimage.<locals>.<genexpr>  s"      #Q#Q2B#Q#Q#Q#Q#Q#Qr+   )r   newadd_blank_pagerq   rt   pagescontents_addr  r  externalize_inline_imagesr   r    nextimagesvaluesr   rw  )rj   tmppdfraw_imgimgs       r,   _convert_to_pdfimagez#PdfInlineImage._convert_to_pdfimage  s   T[(ABBBQ$$z44444;;GDDd 	% 	
 	
 	
 	Q$$T\\^^444 	Q11333vt#Q#Qa1G1N1N1P1P#Q#Q#QQQRR wF###
r+   r   c                N    |                                                                  S )z&Return inline image as a Pillow Image.)r  r   rp   s    r,   r   zPdfInlineImage.as_pil_image  s     ((**77999r+   Nr   rV  r%  rX  rW  r@   c               T    |                                                      ||          S )zxExtract the inline image directly to a usable image file.

        See:
            :meth:`PdfImage.extract_to`
        rV  )r  ra  )rj   r%  rW  s      r,   ra  zPdfInlineImage.extract_to  s2     ((**55j 6 
 
 	
r+   c                N    |                                                                  S )z Return decompressed image bytes.)r  r  rp   s    r,   r  zPdfInlineImage.read_bytes  s"     ((**55777r+   c                N    |                                                                  S )z"Return decompressed stream buffer.)r  r  rp   s    r,   r  z PdfInlineImage.get_stream_buffer  s"     ((**<<>>>r+   )r  r   r  r   r   )rF   r   r   )r%  rX  rW  r@   )r&   r'   r(   r)   r  itemsr  r\   r   r   r  r  rk   r  r   r   r  r  r   ra  r  r  r*   r+   r,   r  r  z  s        ..yz 	% 		
 	 	z 	 	~ 	 	. 	{ 	# 	" 	 	#  	#!" 	#G& 98888OMMM%%%%       0

 

 

 - - [-B B B/ / / /( 
 
 X

 
 
   $: : : : 7;b 
 
 
 
 
 
8 8 8
? ? ? ? ?r+   r  N)r3   r4   )r3   rE   rF   rG   )
rL   rM   rN   r@   rO   rP   rQ   r"   rF   rR   )Cr)   
__future__r   abcr   r   r   decimalr   ior   	itertoolsr	   pathlibr
   shutilr   typingr   r   r   r   r   r   r   PILr   PIL.ImageCmsr   pikepdfr   pikepdf._corer   r   r   r   pikepdf._exceptionsr   pikepdf.modelsr   pikepdf.objectsr   r   r   r   r    r!   r"   r   r   RGBDecodeArrayGrayDecodeArrayCMYKDecodeArrayr   	Exceptionr$   r.   r0   r2   rD   rK   rW   rY   r^   r   r   r  r*   r+   r,   <module>r     s   & % " " " " " " # # # # # # # #                   ! ! ! ! ! !             L L L L L L L L L L L L L L L L L L       ( ( ( ( ( (       B B B B B B B B B B B B / / / / / / ' ' ' ' ' '                GCLLueUE5%?@u%ueUE5%NONO_DEG G G G G	 G G G@ @ @ @ @) @ @ @U U U U U)< U U UJ J J J J9 J J J   (1 1 1 1
= 
= 
= 
=
 
 
 
 
* 
 
 
u  u  u  u  u 3 u  u  u pD
 D
 D
 D
 D
| D
 D
 D
NF
 F
 F
 F
 F
( F
 F
 F
R^? ^? ^? ^? ^?\ ^? ^? ^? ^? ^?r+   