
    OAif              	      r   S r SSKJr  SSKJrJr  SSKJr  SSKJr  SSK	J
r
  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJrJrJrJrJr  SSKJr  SSKJr  SSKJr  SSKJ r J!r!J"r"J#r#  SSK$J%r%  SSK&J'r'  SSK(J)r)  SSK*J+r+J,r,J-r-J.r.J/r/J0r0  \" S5      r1\2\3\3\3\3\3\34   r4\2\3\34   r5\2\3\3\3\3\3\3\3\34   r6\4\5-  \6-  r7 " S S\85      r9 " S S\85      r: " S S\:5      r; " S S\85      r<S,S jr=S-S jr>          S.S jr? " S  S!\5      r@ " S" S#\5      rA " S$ S%\A5      rB " S& S'\B5      rC " S( S)\A5      rD/ S*QrEg+)/zExtract images embedded in PDF.    )annotations)ABCabstractmethod)Callable)copy)Decimal)BytesIO)zip_longest)Path)copyfileobj)AnyBinaryIO
NamedTupleTypeVarcast)Image)ImageCmsProfile)jbig2)BufferPdfPdfErrorStreamDecodeLevel)DependencyError)_transcoding)ImageDecompressionError)Array
DictionaryNameObjectStreamStringTc                      \ rS rSrSrSrg)UnsupportedImageTypeError+   z<This image is formatted in a way pikepdf does not supported. N__name__
__module____qualname____firstlineno____doc____static_attributes__r&       P/var/www/html/land-ocr/venv/lib/python3.13/site-packages/pikepdf/models/image.pyr$   r$   +   s    Fr.   r$   c                      \ rS rSrSrSrg)NotExtractableError/   z5Indicates that an image cannot be directly extracted.r&   Nr'   r&   r.   r/   r1   r1   /   s    ?r.   r1   c                      \ rS rSrSrSrg)"HifiPrintImageNotTranscodableError3   zJImage contains high fidelity printing information and cannot be extracted.r&   Nr'   r&   r.   r/   r4   r4   3   s    Tr.   r4   c                      \ rS rSrSrSrg)InvalidPdfImageError7   z?This image is not valid according to the PDF 1.7 specification.r&   Nr'   r&   r.   r/   r7   r7   7   s    Ir.   r7   c                X   ^ ^ UU 4S jmT" T 5      n[        U[        5      (       d  U/nU$ )zLSimplify pikepdf objects to array of str. Keep streams, dictionaries intact.c                t  > [        U [        [        -  5      (       a  U  Vs/ s H  nT" U5      PM     sn$ [        U [        [        -  [
        -  [        -  5      (       a  U $ [        U [        [        -  5      (       a  [        U 5      $ [        U [        5      (       a  [        U 5      $ [        T5      es  snf N)
isinstancelistr   r    r   bytesintr   strr!   NotImplementedError)itemsubitem_convertvalues     r/   rD   _array_str.<locals>._convert>   s    dD5L))59:T'HW%T::dFZ/%7#=>>KdD3J''t9dV%%;!%(( ;s   B5)r<   r=   )rE   resultrD   s   ` @r/   
_array_strrH   ;   s,    	) e_Ffd##Mr.   c                ~    [        U [        5      (       a  U $ [        U R                  5       R                  5       5      $ )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)rE   s    r/   _ensure_listrL   O   s3     %##%--/00r.   c                r    [        XU5      n U" U5      $ ! [         a    Uc   g Of = f[        SU-   5      e)z@Retrieve metadata from a dictionary or stream and wrangle types.NzMetadata access for )getattr	TypeErrorrA   )objnametype_defaultvals        r/   _metadata_from_objrU   Z   sN     #W
%CSz ;  4t;
<<s    ((c                  .    \ rS rSr% SrS\S'   S\S'   Srg)	PaletteDatag   a%  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>   paletter&   N)r(   r)   r*   r+   r,   __annotations__r-   r&   r.   r/   rW   rW   g   s     Nr.   rW   c                     \ rS rSrSr1 Skr\1 Sk-  rSS1r\S S j5       r	\
S!S j5       r\
S!S	 j5       r\
S"S
 j5       r\
S#S j5       r\
S 5       r\
S 5       r\
S$S j5       r\
S 5       r\
S%S j5       r\
S!S j5       r\
\S&S j5       5       r\
S"S j5       rS r\
S"S j5       r\
S"S j5       r\
S'S j5       rS r\
S(S j5       r\
S 5       r\
S)S j5       r\S*S j5       rS+S jr Sr!g),PdfImageBaset   zAbstract base class for images.>   /CalRGB/CalGray
/DeviceRGB/DeviceGray>   /CalCMYK	/ICCBased/DeviceCMYK/Separation/DeviceNc                    g)z!Get metadata for this image type.Nr&   selfrQ   rR   rS   s       r/   	_metadataPdfImageBase._metadata{       r.   c                0    U R                  S[        S5      $ )z"Width of the image data in pixels.Widthr   rk   r?   rj   s    r/   widthPdfImageBase.width   s     ~~gsA..r.   c                0    U R                  S[        S5      $ )z#Height of the image data in pixels.Heightr   rp   rq   s    r/   heightPdfImageBase.height   s     ~~hQ//r.   c                0    U R                  S[        S5      $ )z)Return ``True`` if this is an image mask.	ImageMaskF)rk   boolrq   s    r/   
image_maskPdfImageBase.image_mask   s     ~~k477r.   c                0    U R                  S[        S5      $ )z.Bits per component for this image (low-level).BitsPerComponentr   rp   rq   s    r/   _bpcPdfImageBase._bpc   s     ~~0#q99r.   c                0    U R                  S[        / 5      $ )zColorspace (low-level).
ColorSpacerk   rH   rq   s    r/   _colorspacesPdfImageBase._colorspaces   s     ~~lJ;;r.   c                0    U R                  S[        / 5      $ )zBList of names of the filters that we applied to encode this image.Filterr   rq   s    r/   filtersPdfImageBase.filters   s     ~~h
B77r.   c                   U R                  S[        / 5      nU(       a/  [        U5      S;   a   [        [        [        S U 5       5      5      $ U R                  S;   a  gU R                  S;   a  gU R                  S:X  a  g	U R                  S
:X  a*  U R                  5       S:X  a  gU R                  5       S:X  a  gU R                  (       a  g[        S[        U 5      -   5      e)zExtract the /Decode array.Decode)         c              3  8   #    U  H  n[        U5      v   M     g 7fr;   )float).0rE   s     r/   	<genexpr>-PdfImageBase._decode_array.<locals>.<genexpr>   s     *LVE5<<Vs   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   rL   lenr   DecodeArraytuple
colorspace_approx_mode_from_iccr{   rA   repr)rj   decodes     r/   _decode_arrayPdfImageBase._decode_array   s     ~~hbAc&kY.U*LV*L%LMM??99??771??m+;??k)))+s2!))+u45??!Cd4jP
 	
r.   c                0    U R                  S[        / 5      $ )z/List of the /DecodeParms, arguments to filters.DecodeParms)rk   rL   rq   s    r/   decode_parmsPdfImageBase.decode_parms   s     ~~m\2>>r.   c                   U R                   (       a  gU R                  (       a  U R                  S   U R                  ;   a  U R                  S   $ U R                  S   S:X  aX  U R                  S   n[        U[        5      (       a  XR                  ;   a  U$ [        U[
        5      (       a  US   S;   a  US   $ U R                  S   S:X  a  g[        S[        U R                  5      -   5      e)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: )r{   r   MAIN_COLORSPACESr<   r@   r=   rA   r   )rj   subspaces     r/   r   PdfImageBase.colorspace   s     ??  #t'<'<<((++  #z1,,Q/h,,=R=R1R#Oh--(1+ B 3 $A;&  #z1!!.d6G6G1HH
 	
r.   c                ~    U R                   b  U R                   S:X  a  U R                  (       a  S$ S$ U R                   $ )z!Bits per component of this image.r   r   r   )r   r{   rq   s    r/   bits_per_componentPdfImageBase.bits_per_component   s3     99		Q1.Q.yyr.   c                    g)z4Return ICC profile for this image if one is defined.Nr&   rq   s    r/   iccPdfImageBase.icc   rm   r.   c                     SU R                   ;   $ )z/Check if the image has a defined color palette.r   )r   rq   s    r/   indexedPdfImageBase.indexed   s     T....r.   c                     U R                   nUS   S:X  a  US   S   U:X  a  gUS   U:X  a  g g! [        [        [        4 a     gf = f)Nr   r   r   TF)r   
IndexErrorAttributeErrorKeyError)rj   rQ   css      r/   _colorspace_has_name!PdfImageBase._colorspace_has_name   sf    	""B!u
"r!uQx4'7!u}   NH5 		s   !0 	0 AAc                $    U R                  S5      $ )<Check if image has a /DeviceN (complex printing) colorspace.rg   r   rq   s    r/   is_device_nPdfImageBase.is_device_n   s     ((44r.   c                $    U R                  S5      $ )r   rf   r   rq   s    r/   is_separationPdfImageBase.is_separation   s     ((77r.   c                2    U R                   U R                  4$ )z!Size of image as (width, height).)rr   rv   rq   s    r/   sizePdfImageBase.size   s     zz4;;&&r.   c                    U R                   (       a  U R                  S   S   nOU R                  S   n[        US   5      nUS:X  a  gSSS.nU R                  R                  R
                  nUR                  US5      $ )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   "PdfImageBase._approx_mode_from_icc   s~    <<++A.q1K++A.K #K$5 6 A% +0!@xx''44%)),;;r.   c                   SnU R                   (       a  SnOU R                  (       a  SnOU R                  (       a  SnOU R                  S:X  a  U R                  S:X  a  SnOjU R                  S:X  a  U R                  S:  a  SnOGU R                  S	:X  a  S
nO4U R                  S:X  a  SnO!U R                  S:X  a   U R                  5       nUS:X  a  [        S5      SeU$ ! [        [        4 a  n[        S5      UeSnAff = f)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   
ValueErrorrO   rA   )rj   mes      r/   modePdfImageBase.mode  s     AA\\A__-$2I2IQ2NA__-$2I2IA2MA__,A__-A__+..0
 7%?  	* )Cs   <C   D0C<<Dc                R    [        [        U R                  U R                  0 S95      $ )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   rq   s    r/   filter_decodeparmsPdfImageBase.filter_decodeparms2  s"     Kd.?.?2NOOr.   c                n   U R                   (       d  g U R                  u  pp4U R                  (       d7  U R                  (       d&  U R
                  (       d  [        U[        5      (       a  [        US   5      nO[        U5      n[        U5      nX R                  ;  a  X R                  ;  a  [        SU 35      eUS;   a  SnOIUS;   a  SnO@US	:X  a  S
nO7US:X  a  SnO.US:X  a  SnO%US:X  a  U R                  5       nO[        SU 35      e[        X$5      $ ! [         a  n[        S5      UeSnAff = f)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   rW   )rj   _idxbase_hivallookupr   s         r/   rZ   PdfImageBase.paletteB  s0    ||	N)-):):&D 88t''4+=+=DRVAWAWtAw<Dt9Dv,,,=S=S1S%(PQUPV&WXX,,D00D]"DZD]"D[ --/D%(PQUPV&WXX4((/  	NEFAM	Ns   D 
D4#D//D4c                    g)z6Convert this PDF image to a Python PIL (Pillow) image.Nr&   rq   s    r/   as_pil_imagePdfImageBase.as_pil_imageb  rm   r.   c                    [        5       nU R                  5        nUR                  US5        UR                  5       sSSS5        $ ! , (       d  f       g= f)z!Display hook for IPython/Jupyter.PNGN)r	   r   savegetvalue)rj   bims      r/   
_repr_png_PdfImageBase._repr_png_f  s:    I BGGAu::< !  s   "A
Ar&   N)rQ   r@   rR   Callable[[Any], T]rS   r"   returnr"   r   r?   r   rz   )r   z
int | None)r   r   )r   
str | Noner   ImageCmsProfile | None)r   ztuple[int, int])r   r@   )r   zPaletteData | Noner   zImage.Imager   r>   )"r(   r)   r*   r+   r,   SIMPLE_COLORSPACESr   r   r   rk   propertyrr   rv   r{   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rZ   r   r   r-   r&   r.   r/   r]   r]   t   s   )M),TT&
30 0 / / 0 0 8 8 : : < < 8 8 
 
0 ? ? 
 
2   C  C / /	 5 5 8 8 ' '<    D P P ) )> E E r.   r]   c                  |  ^  \ rS rSr% SrS\S'   S\S'   S\S'   S#U 4S	 jjrS#S
 jrS r\	S 5       r
S r\S 5       r\S$S j5       rS rS%S jrS&S jrS&S jrS&S jrS&S jrS'S jrSSS.     S(S jjr\R0                  4   S)S jjr\R0                  4   S*S jjrS&S jrS+S,S jjrS rS-S  jrS! rS"r U =r!$ ).PdfImagein  aq  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    rP   r   _iccz
Pdf | None_pdf_sourcec                   >  [        UR                  5      n[        R                  U;   a  [        TU ]  [        5      $  [        TU ]  [        5      $ ! [        [        4 a     N%f = f)zGConstruct a PdfImage... or a PdfJpxImage if that is what we really are.)
rL   r   r   	JPXDecodesuper__new__PdfJpxImager   r   r   )clsrP   r   	__class__s      r/   r  PdfImage.__new__|  s`    	"3::.G~~(w{33 )
 wx(( ) 		s   ;A A&%A&c                    [        U[        5      (       a*  UR                  R                  S5      S:w  a  [	        S5      eXl        SU l        g)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   rO   rP   r   )rj   rP   s     r/   __init__PdfImage.__init__  s?     c6""s':'::'F('REFF	r.   c                j    [        U[        5      (       d  [        $ U R                  UR                  :H  $ r;   )r<   r]   NotImplementedrP   rj   others     r/   __eq__PdfImage.__eq__  s(    %..!!xx599$$r.   c                  UR                  5       n[        X5      n[        S5      Ul        [        S5      Ul        UR
                  S:X  a  [        S5      Ul        O UR
                  S;   a  [        S5      Ul        UR
                  S:X  a  SOS	Ul        UR                  Ul	        UR                  Ul        XbR                  R                  U'   U " U5      $ )
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~   rr   ro   rv   ru   	ResourcesXObject)r  pdfpagerQ   imagedataimstreams          r/   _from_pil_imagePdfImage._from_pil_image  s     }}#$Z(>::"&|"4HZZ:%"&}"5H).s):A!,,'/t$8}r.   c                0    [        U R                  XU5      $ r;   rU   rP   ri   s       r/   rk   PdfImage._metadata      !$((DAAr.   c                    U R                   S:X  aV  U R                  (       d  U R                  S   $ [        U R                  S   [        5      (       d   eU R                  S   S   $ [        S5      e)Nrd   r   z+Don't know how to find ICC stream for image)r   r   r   r<   r=   rA   rq   s    r/   
_iccstreamPdfImage._iccstream  sf    ??k)<<((++d//2D9999$$Q'**!"OPPr.   c                `   U R                   S;  a  gU R                  (       dD  U R                  nUR                  5       n[	        U5      n [        U5      U l        U R                  $ U R                  $ ! [         a0  n[        U5      S:X  a  [        S5      Ue SnAU R                  $ SnAff = f)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   PdfImage.icc  s     ??";;yyI!335I +J+J7	 yytyy  q6>>3= ?
 yys   A3 3
B-=B((B-c                   1 Skn[        U R                  5       VVs/ s H  u  p#X1;   d  M  UPM     nnn[        U5      S:  a0  [        SU R                  R
                   SU R                   S35      e[        U5      S:X  a+  U R                  R                  [        R                  5      / 4$ US   nUS:X  a&  U R                  R                  5       U R                  4$ [        U R                  5      n[        U R                  SU  Vs/ s H  n[        U5      PM     sn5      Ul        [        U R                  SU 5      Ul        UR                  [        R                  5      U R                  US 4$ s  snnf s  snf )z4Remove simple lossless compression where it appears.>   
/DCTDecode
/JPXDecode/JBIG2Decode/CCITTFaxDecoder   zObject z has compound complex filters: z. We cannot decompress this.r   N)	enumerater   r   rA   rP   objgen
read_bytesr   specializedread_raw_bytesr   r   r   r   r   r   )rj   COMPLEX_FILTERSnfiltindicesobj_copyfs          r/   _remove_simple_filtersPdfImage._remove_simple_filters  sR   
 %.dll$;W$;t?V1$;Ww<!%$((//**I<<. <>  w<188&&'8'D'DErIIAJ688**,dll::>$,,r2B C2BQa2B CD$T%6%6r%:;""#4#@#@A4<<PQPRCSSS% X  !Ds   E6E6
E<c                 ^  SU 4S jjnSU 4S jjnT R                  5       u  pEUS/:X  a]  T R                  S:X  a  T R                  R                  5       nOSnUR	                  T R                  XFS95        UR	                  U5        gUS/:X  a:  T R                  S	:X  d  U" 5       (       d  U" 5       (       a  UR	                  U5        g
g)a#  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
c                    > Sn U nTR                   S   S   b"  TR                   S   S   R                  SU 5      nTR                  S:H  =(       a    X:H  $ )Nr   r   /ColorTransformr   r   r   r   )DEFAULT_CT_RGBctrj   s     r/   normal_dct_rgb0PdfImage._extract_direct.<locals>.normal_dct_rgb  sc     NB&&q)!,8,,Q/266%~ 99%>"*>>r.   c                    > Sn U nTR                   S   S   b"  TR                   S   S   R                  SU 5      nTR                  S:H  =(       a    X:H  $ )Nr   r   rC  r   rD  )DEFAULT_CT_CMYKrF  rj   s     r/   normal_dct_cmyk1PdfImage._extract_direct.<locals>.normal_dct_cmyk  sc      O B&&q)!,8,,Q/266% 99&@2+@@r.   r3  rd   N)r   z.tifr0  r   z.jpgr   )r?  r   r&  r6  write_generate_ccitt_headerr   )rj   streamrG  rK  r  r   r   s   `      r/   _extract_directPdfImage._extract_direct  s    	?		A 335())+-oo002LL44T4CDLL|n$II 0 0O4E4ELLr.   c                &   SnU R                   S:X  a  SOSnU R                  S;   a>  [        R                  " U R	                  5       U R
                  U R                  U5      u  p1O:U R                  S:X  a  [        [        U R                  5       5      nO[        S5      eU R                   S:X  aA  U R                  b4  U R                  u  pE[        R                  " UU R
                  UUU5      nU$ [        R                  " X0R
                  U5      nU$ )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_pixelsr6  r   r   
memoryviewr)  r7   rZ   image_from_buffer_and_paletteimage_from_byte_buffer)rj   stridescalebuffer	base_moderZ   r   s          r/   _extract_transcoded_1248bits%PdfImage._extract_transcoded_1248bits)  s    YY#%1""f,)??!499d.E.EuNFF $$)*d&<&<&>?F&'STT99 8!%I;;		B 	 44VYYOB	r.   c                   U R                   (       d  U R                  S;   a  [        S5      e U R                  5       n[        R                  " SU R                  U5      nU R                  b%  U R                  u  pE[        R                   " X4U5      nU$ ! [        [
        4 aI  nS[        U5      ;   a4  [        R                  " 5       R                  5       (       d  [        S5      S ee S nAff = f)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   )r{   r   r$   r6  RuntimeErrorr   r@   r   get_decoder	availabler   r   	frombytesr   rZ   r   fix_1bit_palette_image)rj   r  r   r   r[  rZ   s         r/   _extract_transcoded_1bit!PdfImage._extract_transcoded_1bitC  s    499#?+,RSS	??$D __S$))T2<<#!%I44RGLB	# h' 		:c!fD))+5577%0  		s   B C-$AC((C-c                "    U R                  5       $ r;   )rd  rq   s    r/   _extract_transcoded_mask!PdfImage._extract_transcoded_mask[  s    ,,..r.   c           	     V   U R                   (       a  U R                  5       $ U R                  S;   a
  [        5       eU R                  S:X  aE  U R                  S:X  a5  [
        R                  " SU R                  U R                  5       SSSS5      nOU R                  S:X  aE  U R                  S:X  a5  [
        R                  " SU R                  U R                  5       SSSS5      nOU R                  S:X  a  U R                  5       nO^U R                  S;   a!  U R                  S::  a  U R                  5       nO-[        [        U 5      S	-   [        U R                  5      -   5      eU R                  S
:X  a4  U R                   b'  U R                   R#                  5       UR$                  S'   U$ )N>   r   r   r   r   rawr   r   r   )r   r   z, rd   r   )r{   rg  r   r4   r   r   
frombufferr   r6  r)  rd  r\  r$   r   rP   r   r   r  info)rj   r   s     r/   _extract_transcodedPdfImage._extract_transcoded^  sU   ??0022991146699$"9"9Q"> !!tyy$//"3UE1aB YY& T%<%<%A!!		4#9#9#;UFAqB $$)..0BYY*$)@)@A)E224B+DJ,=TXX,NOO??k)dhh.B%)XX%5%5%7BGGM"	r.   c               0   U R                  US9nU(       a  U$ Sn U R                  5       nUR                  S:X  a+  UR                  USSS9   U(       a  UR	                  5         ggU(       a*  UR                  USS	9   U(       a  UR	                  5         g
g
 U(       a  UR	                  5         [        [        U 5      5      e! [
         a*  nS[        U5      ;   a  [        [        U 5      5      Uee SnAff = f! U(       a  UR	                  5         f f = f)ag  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.
rO  Nr   tifftiff_adobe_deflate)formatcompressionz.tiffpng)rs  z.pngzcalled on unfilterable stream)	rP  rm  r   r   closer   r@   r$   r   )rj   rO  direct_extractionr   r   s        r/   _extract_to_streamPdfImage._extract_to_stream|  s    !000?$$	))+Bww& v;OP 
  u- 
   
'T
33  	.#a&8/T
;B	
 
 s)   1C 'C 
C8%C33C88C; ;DNr   rO  
fileprefixc                  [        U5      [        U5      :X  a  [        S5      eU(       a  U R                  US9$ [        5       nU R                  US9nUR	                  S5        [        [        [        U5      5      U-   5      nUR                  S5       n[        X65        SSS5        [        U5      $ ! , (       d  f       N= f)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 fileprefixrp  r   wbN)	rz   r   rx  r	   seekr   r@   openr   )rj   rO  r{  bio	extensionfilepathtargets          r/   
extract_toPdfImage.extract_to  s    D <4
++DEE**&*99i++3+7	D,-	9:]]4 F$ !8} ! s   B44
Cc                4    U R                   R                  US9$ )z7Decompress this image and return it as unencoded bytes.decode_level)rP   r6  rj   r  s     r/   r6  PdfImage.read_bytes  s     xx"""==r.   c                4    U R                   R                  US9$ )z+Access this image with the buffer protocol.r  )rP   r)  r  s     r/   r)  PdfImage.get_stream_buffer  s     xx))|)DDr.   c                    [        5       nU R                  US9nU(       a'  UR                  S5        [        R                  " U5      $ U R                  5       nU(       d  [        [        U 5      5      eU$ )zeExtract the image as a Pillow Image, using decompression as necessary.

Caller must close the image.
rp  r   )r	   rP  r~  r   r  rm  r$   r   )rj   r  rw  r   s       r/   r   PdfImage.as_pil_image  s`    
 i 000<HHQK::c?"%%'+DJ77	r.   c           	     0   U R                   (       d  [        S5      eS/nU H8  u  pEU R                   S   R                  XE5      U:w  d  M)  [        SU SU 35      e   U R                   S   R                  SS5      nSnUS:  a  SnOUS:  a  S	nS
nOS	nU R                   S   R                  SS5      n	U R                  n
U	(       a  S
OSn[        U
5      S:X  a  U
S:X  a  S
U-
  n[        U5      nUc  Sn[        R                  " U R                  UUUUUS9$ )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/KNrS     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_defaultsrQ   rT   kr  r  black_is_oner   r  img_sizes                r/   rN  PdfImage._generate_ccitt_header  sB   
   CDD )
 +ID  #''2c9/<TF+cUS  + a $$T1-
q5KUKJK((+//UC## 'QA
 v;!* 4ZJt9;C11II #!!
 	
r.   c                @    U R                  5       R                  5         g)z$Show the image however PIL wants to.N)r   showrq   s    r/   r  PdfImage.show#  s      "r.   c                    Xl         g r;   )r   )rj   r  s     r/   _set_pdf_sourcePdfImage._set_pdf_source'  s    r.   c                     U R                   nSU SU R                   SU R                   S[	        [        U 5      5       S3	$ ! [         a    Sn NCf = f)N?z<pikepdf.PdfImage image mode= size=x at >r   rA   rr   rv   hexidrj   r   s     r/   __repr__PdfImage.__repr__*  sb    	99D ,D6 2JJ<qT#bh-C	
 # 	D	   A AA)r   r   rP   )rP   r    r   rO  r   r   r   r   )rO  r   r   r@   )rO  BinaryIO | Noner{  r@   r   r@   )r  r   r   r>   )r  r   r   r   r;   )r  r>   r   zbytes | Noner   r>   )r  r   )"r(   r)   r*   r+   r,   r[   r  r  r  classmethodr  rk   r   r&  r   r?  rP  r\  rd  rg  rm  rx  r  r   r7  r6  r)  r   rN  r  r  r  r-   __classcell__r  s   @r/   r   r   n  s    
K
  
)%
  4B Q Q  *T84l40/<#4L ,02-(-=@-	-` 1B0M0M>->	> 1B0M0ME-E	E"4
l#
 
r.   r   c                     ^  \ rS rSrSrU 4S jrS rSS jrSU 4S jjr\	U 4S j5       r
\	SS j5       r\	SS	 j5       rS
 rSrU =r$ )r  i5  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                N   > [         TU ]  U5        U R                  5       U l        g)zInitialize a JPEG 2000 image.N)r  r  r   _jpxpil)rj   rP   r  s     r/   r  PdfJpxImage.__init__<  s     ((*r.   c                    [        U[        5      (       d  [        $ U R                  UR                  :H  =(       a0    [        U[        5      =(       a    U R
                  UR
                  :H  $ r;   )r<   r]   r  rP   r  r  r  s     r/   r  PdfJpxImage.__eq__A  sN    %..!!HH		! .5+..-	
r.   c               Z    U R                  5       u  p#US/:w  a  g UR                  U5        g)Nr1  z.jp2)r?  rM  )rj   rO  r  r   s       r/   rP  PdfJpxImage._extract_directJ  s.    335|n$Tr.   c                    > [         TU ]  5       $ r;   )r  rm  )rj   r  s    r/   rm  PdfJpxImage._extract_transcodedQ  s    w*,,r.   c                   > [         TU ]  nU(       a  U$ U R                  R                  S:X  a  S/$ U R                  R                  S:X  a  S/$ [	        S5      e)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   PdfJpxImage._colorspacesT  sY     "G0$$<<#!?"<<% >!!":;;r.   c                    g)z=Return 8, since bpc is not meaningful for JPEG 2000 encoding.r   r&   rq   s    r/   r   PdfJpxImage._bpcf  s     r.   c                    g)z4Return False, since JPEG 2000 should not be indexed.Fr&   rq   s    r/   r   PdfJpxImage.indexedo  s     r.   c                    SU R                    SU R                   SU R                   S[        [	        U 5      5       S3	$ )Nz)<pikepdf.PdfJpxImage JPEG2000 image mode=r  r  r  r  )r   rr   rv   r  r  rq   s    r/   r  PdfJpxImage.__repr__w  sA    7		{ CJJ<qT#bh-C	
r.   )r  r  r   r   r   )r(   r)   r*   r+   r,   r  r  rP  rm  r   r   r   r   r  r-   r  r  s   @r/   r  r  5  sb    +

- < <"    
 
r.   r  c                  n   \ rS rSr% Sr0 SS_SS_SS_S	S
_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS _S!S"_S#S$_r\R                  5        V VVs0 s H  u  pX!_M	     snnn rS%\S&'   S'\S('   S9S) jr	S* r
\S+ 5       rS, rS:S- jr\S. 5       rS/ rS;S0 jrS<S1 jrS2S3S4.S=S5 jjrS6 rS7 rS8rg2s  snnn f )>PdfInlineImagei~  z$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
   /DCTDecoder   _dataztuple[Object, ...]_image_objectc                  ^  UT l         UT l        SR                  U 4S jU 5       5      n [        R                  " SU-   S-   5      nUT l        g! [
         a#  n[        SUR                  S5      -   5      UeSnAff = f)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  X   >#    U  H  nTR                  UTR                  S 9v   M!     g7f)remap_namesN)_unparse_objABBREVS)r   rP   rj   s     r/   r   *PdfInlineImage.__init__.<locals>.<genexpr>  s(      
HTDct||<s   '*s   << s    >>zparsing inline unicode_escapeN)r  r  joinr   parser   r   rP   )rj   
image_dataimage_objectreparsereparsed_objr   s   `     r/   r  PdfInlineImage.__init__  s      
))) 
HT
 
	X!<<(86(ABL    	X,w~~>N/OOPVWW	Xs   A 
A=A88A=c                   [        U[        5      (       d  [        $ U R                  UR                  :H  =(       aL    [        U[        5      =(       a5    U R
                  R                  5       UR
                  R                  5       :H  $ r;   )r<   r]   r  rP   r  r  _inline_image_raw_bytesr  s     r/   r  PdfInlineImage.__eq__  se    %..!!HH		! 5.1 

224;;6689		
r.   c                   [        U[        5      (       a[  [        U[        5      (       a7  UR                  SS9n[        U[        5      (       d   eUR                  X35      $ UR                  SS9$ [        U[        5      (       a  U(       a  S$ S$ [        U[        [        -  [        -  5      (       a  [        U5      R                  S5      $ [        [        U5      5      e)NT)resolveds   trues   falseascii)r<   r   r   unparser>   r   rz   r?   r   r   r@   encoderA   r   )r  rP   r  rQ   s       r/   r  PdfInlineImage._unparse_obj  s    c6""#t$${{D{1!$...."t22;;;--c4  !7/x/c3=5011s8??7++!$s),,r.   c                0    [        U R                  XU5      $ r;   r"  ri   s       r/   rk   PdfInlineImage._metadata  r$  r.   c                L   ^ ^ U 4S jmUU 4S jnSR                  U" 5       5      $ )zACreate the content stream bytes that reproduce this inline image.c               3     >#    TR                    H8  n TR                  U TR                  S9n[        U[        5      (       d   eUv   M:     g 7f)Nr  )r  r  REVERSE_ABBREVSr<   r>   )metadata_objunparsedrj   s     r/   metadata_tokens/PdfInlineImage.unparse.<locals>.metadata_tokens  sP      $ 2 2,, d.B.B -  "(E2222 !3s   A
Ac               3     >#    Sv   SR                  S T " 5        5       5      v   Sv   TR                  R                  5       v   Sv   g 7f)Ns   BI
r  c              3  $   #    U  H  ov   M     g 7fr;   r&   )r   r   s     r/   r   FPdfInlineImage.unparse.<locals>.inline_image_tokens.<locals>.<genexpr>  s     9'8!A'8   s   
ID
s   EI)r  r  r  )r  rj   s   r/   inline_image_tokens3PdfInlineImage.unparse.<locals>.inline_image_tokens  s@     M))9'8999O**4466Ks   A	Ar.   )r  )rj   r  r  s   ` @r/   r  PdfInlineImage.unparse  s"    		 xx+-..r.   c                    [        S5      e)zIRaise an exception since ICC profiles are not supported on inline images.zJInline images with ICC profiles are not supported in the PDF specification)r7   rq   s    r/   r   PdfInlineImage.icc  s     #X
 	
r.   c                     U R                   nSU SU R                   SU R                   S[	        [        U 5      5       S3	$ ! [         a    Sn NCf = f)Nr  z#<pikepdf.PdfInlineImage image mode=r  r  r  r  r  r  s     r/   r  PdfInlineImage.__repr__  sb    	99D 2$ 8JJ<qT#bh-C	
 # 	D	r  c                Z   [         R                  " 5       nUR                  U R                  U R                  4S9  UR
                  S   R                  U R                   SU R                   S3R                  S5      SS9  UR
                  S   R                  U R                  5       5        UR
                  S   R                  5         [        [        [        S UR
                  S   R                  R                  5        5       5      5      n[        U5      nUR!                  U5        U$ )	N)	page_sizer   z 0 0 z 0 0 cmr  T)prependc              3  $   #    U  H  ov   M     g 7fr;   r&   )r   r   s     r/   r   6PdfInlineImage._convert_to_pdfimage.<locals>.<genexpr>  s     #Q1P2B1Pr  )r   newadd_blank_pagerr   rv   pagescontents_addr  r  externalize_inline_imagesr   r    nextimagesvaluesr   r  )rj   tmppdfraw_imgimgs       r/   _convert_to_pdfimage#PdfInlineImage._convert_to_pdfimage  s    T[[(ABQ$$zzl%}G4;;GDd 	% 	
 	Q$$T\\^4 	Q113vt#Qa1G1G1N1N1P#QQR wF#
r.   c                >    U R                  5       R                  5       $ )z&Return inline image as a Pillow Image.)r  r   rq   s    r/   r   PdfInlineImage.as_pil_image  s    ((*7799r.   Nr   rz  c               <    U R                  5       R                  XS9$ )z`Extract the inline image directly to a usable image file.

See:
    :meth:`PdfImage.extract_to`
rz  )r  r  )rj   rO  r{  s      r/   r  PdfInlineImage.extract_to
  s(     ((*55 6 
 	
r.   c                >    U R                  5       R                  5       $ )z Return decompressed image bytes.)r  r6  rq   s    r/   r6  PdfInlineImage.read_bytes  s     ((*5577r.   c                >    U R                  5       R                  5       $ )z"Return decompressed stream buffer.)r  r)  rq   s    r/   r)   PdfInlineImage.get_stream_buffer  s     ((*<<>>r.   )r  r  rP   )r  r   r  r   r   )r   r   r   )rO  r  r{  r@   )r(   r)   r*   r+   r,   r  itemsr  r[   r  r  r  r  rk   r  r   r   r  r  r   r  r6  r)  r-   )r   r  vs   000r/   r  r  ~  sl   .yz 	% 		
 	 	z 	 	~ 	 	. 	{ 	# 	" 	 	#  	#!" 	#G& )08qt8OM%% 0

 - -B/( 
 

$: 7;b 
8
?I 9s   B0r  )CMYKDecodeArrayr   r4   r   r7   rW   r   r]   r  r  RGBDecodeArrayr$   N)rE   zObject | str | list)rE   z*list[Object] | Dictionary | Array | Objectr   zlist[Object])
rP   zDictionary | StreamrQ   r@   rR   r   rS   r"   r   zT | None)Fr,   
__future__r   abcr   r   collections.abcr   r   decimalr   ior	   	itertoolsr
   pathlibr   shutilr   typingr   r   r   r   r   PILr   PIL.ImageCmsr   pikepdfr   pikepdf._corer   r   r   r   pikepdf._exceptionsr   pikepdf.modelsr   pikepdf.models._transcodingr   pikepdf.objectsr   r   r   r   r    r!   r"   r   r   r  GrayDecodeArrayr  r   	Exceptionr$   r1   r4   r7   rH   rL   rU   rW   r]   r   r  r  __all__r&   r.   r/   <module>r)     sf   & " # $    !   ; ;  (  B B / ' ?  CLueUE5%?@u%ueUE5%NO.@G	 G@) @U)< UJ9 J(1
=	
=$'
=0B
=MN
=
=
* 
w 3 w tD
| D
NF
( F
R^?\ ^?Br.   