
    '	4js                     H   U d dl Z d dlZd dlZd dlZd dl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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 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+ e+jX                  Z-erd dl*m$Z/ d dl0m1Z1 neZ/ee2d<   	 d dl3Z3e G d d             Z4 ejj                  e6      Z7dZ8 e4       Z9g dZ:dZ;dZ<dZ=dZ>	 d;dede"dee?e@e@f      de?eAee deBeedf   eez  f   fdZCdeBdeDfd ZEd!edee/   fd"ZFd#eAez  ez  defd$ZGd%eAdefd&ZHed'eBd#eAez  deDfd(       ZId#eAd)edede?eAe ef   fd*ZJ	 	 	 d<d#eeAeef   d)edeBeeeAdf   d+edee?e@e@f      def
d,ZK G d- d.      ZLd)dde?eMeMf   fd/ZNd)ddeBfd0ZO	 	 d=d)dd1ePdz  d2ePdz  deBfd3ZQd4eeM   deBfd5ZRde?eSeBeMf   eMeMeMf   fd6ZTd)dd+ed7edeBfd8ZU	 	 d=d)dd1ePdz  d2ePdz  deBfd9ZVd)ddeDfd:ZWy# e)$ r dZ$dZ%dZ&dZ(Y w xY w# e)e.f$ r dZ-Y w xY w# e)$ r dZ3Y }w xY w)>    N)	dataclass)BytesIO)ceil)Path)	TYPE_CHECKINGAnyBinaryIOIterableOptional	TypeAlias	TypeGuardUnionno_type_check)urlopen   )FPDFException)
ImageCacheImageFilterRasterImageInfoVectorImageInfo)	SVGObject)	ImageType)ImageImageCmsTiffImagePluginfeatures)
Resampling)r   )ImageCmsProfilePILImagec                       e Zd ZU dZeed<   y)ImageSettingscompression_levelN)__name__
__module____qualname__r#   int__annotations__     ?/DATA/.local/lib/python3.12/site-packages/fpdf/image_parsing.pyr!   r!   >   s      sr*   r!   )AUTOFlateDecode	DCTDecode	JPXDecode	LZWDecode(   r      @             `            P      0      p            H      (      h            X      8      x            D      $      d            T      4      t            L      ,      l            \      <      |            B      "      b            R      2      r      
      J      *      j            Z      :      z            F      &      f            V      6      v            N      .      n            ^      >      ~      r      A      !      a            Q      1      q      	      I      )      i            Y      9      y            E      %      e            U      5      u            M      -      m            ]      =      }            C      #      c            S      3      s            K      +      k            [      ;      {            G      '      g            W      7      w            O      /      o            _      ?               i  r   r`   image_cachenamedimsreturnc                 *   t        |t        t        f      rDt        |      j                  d      r*	 t	        t        |      t        t        |            |       S t        |t              r:t        |j                               r!t	        dt        j                  |      |       S t        |t        j                        r5t        |j                         j                               rt	        d||       S t        |t              r|d}}nt        |      rK|j                         }t!        j"                  dd      }|j%                  |       |j'                         |}}nt        |t        t        j                  f      rwt        |t        j                        r|j                         n|}|j                         }t!        j"                  dd      }|j%                  |       |j'                         |}}nt        |      d}}| j(                  j+                  |      }||d	   d
z   |d	<   nt-        ||| j.                  |      }t1        | j(                        d
z   |d<   d
|d	<   d|d<   |j+                  d      }	|	et2        j5                  d|       |	| j6                  v r| j6                  |	   |d<   n)t1        | j6                        }
|
| j6                  |	<   |
|d<   d|d<   || j(                  |<   |||fS # t        $ r}t        d|       |d}~ww xY w)ao  
    Read an image and load it into memory.

    For raster images: following this call, the image is inserted in `image_cache.images`,
    and following calls to `fpdf.fpdf.FPDF.image()` will re-use the same cached values, without re-reading the image.

    For vector images: the data is loaded and the metadata extracted.

    Args:
        image_cache: an `ImageCache` instance, usually the `.image_cache` attribute of a `FPDF` instance.
        name: either a string representing a file path to an image, an URL to an image,
            an io.BytesIO, or a instance of `PIL.Image.Image`.
        dims (tuple[int, int]): optional dimensions as a tuple (width, height) to resize the image
            (raster only) before storing it in the PDF.

    Returns: A tuple, consisting of 3 values: the name, the image data,
        and an instance of a subclass of `ImageInfo`.
    z.svgr0  zCould not parse file: Nvector_imagemd5F)usedforsecurityusagesr   iiccp_iiccpzHICC profile found for image %s - It will be inserted in the PDF document)
isinstancestrr   endswithget_svg_info
load_image	Exception
ValueErrorbytes_is_svgstripior   getvalue_is_pil_imagetobyteshashlibnewupdate	hexdigestimagesgetget_img_infoimage_filterlenLOGGERdebugicc_profiles)r0  r1  r2  errorraster_nameimgbytes_img_hashinfor<  r;  s              r+   preload_imager]  n   s   8 $d$T););F)C	ID	:c$i0k 
 $74::<#8NBJJt,<+VV$

#0E0E0G(HNDkJJ
 $S	t	;;ue<#--/S	D5"**-	.$.tRZZ$@d;;ue<#--/St9dS5@5G5G5K5KK5XDh!+X$$	
 **+a/S	XXxxLLZ {///!,!9!9$!?X[55617((.!'XDL*.;'T!!i  	I5dV<=5H	Is   (K5 5	L>LLrZ  c                 J    | j                  d      xs | j                  d      S )Ns   <?xml s   <svg )
startswith)rZ  s    r+   rE  rE     s#    Y'F6+<+<X+FFr*   objc                 J    t         d uxr t        | t         j                         S N)r   r=  )r`  s    r+   rI  rI     s    =C!==r*   filenamec                 @   t        | t        t        j                  t        f      r| S t        | d      r/t        | t        t        f      st        | j                               S t        | t              rt        |       } | j                  d      r.t        |       5 }t        |j                               cddd       S | j                  d      rt        |       S t        | d      5 }t        |j                               cddd       S # 1 sw Y   8xY w# 1 sw Y   yxY w)z
    This method is used to load external resources, such as images.
    It is automatically called when resource added to document by `fpdf.fpdf.FPDF.image()`.
    It always return a BytesIO buffer.
    read)zhttp://zhttps://Nzdata:rb)r=  r   rG  BufferedIOBaser	   hasattrr>  r   re  r_  r   _decode_base64_imageopen)rc  url_file
local_files      r+   rA  rA     s     (Wb&7&7BCx HsDk)Jx}}''(D!x=23 X(8==?+ 			W	%#H--	h	z() 
		  
	s   D%DDDbase64Imagec                     | j                  d      }t        |      dk7  rt        d      |d   }t        j                  |      }t        |      S )z7Decode the base 64 image string into an io byte stream.zbase64,rp   z!Unsupported non-base64 image datar   )splitrS  NotImplementedErrorbase64	b64decoder   )rm  frags	imageDatadecodedDatas       r+   ri  ri     sM    i(E
5zQ!"EFFaI""9-K;r*   r<  c                 2   	 t        j                  t        |             }t        |j                  j                        j                         }|dvrt        j                  d||       yy# t         j                  $ r t        j                  d|       Y yw xY w)z%Checks the validity of an ICC profilezInvalid ICC Profile in file %sF)GRAYRGBzEUnsupported color space %s in ICC Profile of file %s - cf. issue #711T)
r   getOpenProfiler   
PyCMSErrorrT  r\  r>  profilexcolor_spacerF  )r<  rc  r{  color_spaces       r+   is_iccp_validr~     s    %-%<%<WT]%K goo22399;K/)S	

   4h?s   A* *)BBrY  c                 (   |j                  d       |j                         }t        ||      }|j                  r|j                  \  }}}}ndx}}|j                  r|j                  }|j
                  r|j
                  }t        |||      }| ||fS )Nr   r5  g        )datawh)seekre  r   viewboxwidthheightr   )	rc  rY  r0  svg_datasvg_r  r  r\  s	            r+   r@  r@    s     HHQKxxzH
H+
6C
{{[[
1aA
yyII
zzJJqA.DS$r*   rR  c                    t         t        d      d}d}d}d}|rt        |t        t        f      r#t        |       }t        j                  |      }d}nTt        |      sIt        |t              }t        |t              rt        |      }n|}|J t        j                  |      }d}t        |      sJ d}|r|j                  |t              }d}|dk(  r;|j                  dk(  rd}n)|j                  d	k(  rt        j                  d
      rd}nd}|j                  dv r|dk7  r|j!                  d      }|j                  dvr|j!                  d      }d}|j                  dv r|dk(  r|j!                  d      }n$|j                  dv r|dk(  r|j!                  d      }|j"                  \  }	}
t%               }d}d|j&                  v r(t)        |j&                  d   |       r|j&                  d   }|[|sX|j                  dk(  r|dk(  r|j                  dv rd\  }}}nF|j                  dk(  r	d\  }}}d}n.|j                  dk(  rd\  }}}nt+        d|j                         |j-                  d       |j/                  |j1                         |	|
||||||d| d|	 d
       |S |j                  d k(  r|dk(  r|j&                  d!   d"k(  r}t3        |j4                  t6        j8                           d#k(  rSt3        |j4                  t6        j:                           d#k(  r)|j4                  t6        j<                     }d}|dk(  rd}n|d#k7  rt+        d$|       t?        |      \  }}|j-                  |       |j1                  |      }|j4                  jA                  t6        jB                        }||d#k(  rnI|d%k(  r6tE        |      }tG        |      D ]  \  }}tH        |   ||<    t        |      }nt+        d&|       d'\  }}}|j/                  ||	|
d|||||d(t	        |       jK                          d|	 d)|
 d*
       |S d}|j                  d	k(  rd'\  }}}tM        ||      |d+<   n |j                  dk(  rd\  }}}tM        ||      |d+<   n|j                  dk(  rHd\  }}}tO        d#dd%      }tM        |||,      |d+<   tQ        |      r|d-vrtM        |||.      |d/<   n|j                  d0k(  rd1\  }}}tM        ||      |d+<   |jR                  |jR                  jR                  nd|d2<   |j&                  jA                  d3d      ;|d-vr6tM        |j!                  d      |tO        d4dd5      .      |d/<   n	|j                  d6k(  rld1\  }}}|jR                  |jR                  jR                  nd|d2<   tO        d#dd%      }tM        |||,      |d+<   tQ        |      r|d-vrtM        |||.      |d/<   n|j                  dk(  rd\  }}}tM        ||      |d+<   ni|j                  dk(  rd\  }}}tM        ||      |d+<   nDd\  }}}tO        d4dd5      }tM        |||,      |d+<   tQ        |      r|d-vrtM        |||.      |d/<   d| d|	 }|j                  d	k(  rd7|	 d)|
 }|s |rtU        |d8d       n|jW                          |j/                  |	|
|||||||d9	       |S ):z
    Args:
        filename: in a format that can be passed to load_image
        img: optional `bytes`, `BytesIO` or `PIL.Image.Image` instance
        image_filter (str): one of the SUPPORTED_IMAGE_FILTERS
    Nz1Pillow not available - fpdf2 cannot insert imagesTF)resampler,   JPEGr.   1libtiffCCITTFaxDecoder-   )PPARGBA)r  LLArx  r  r  r  CMYK)r  r  r0   rx  r  r  icc_profile)rx  r  )r   r@   	DeviceRGBr  )rP   r@   
DeviceCMYK)r   r@   
DeviceGrayzUnsupported image mode: r   z/Predictor 15 /Colors z
 /Columns )
r  r  r  csr<  dpnbpcfinverteddpTIFFcompressiongroup4r   z4unsupported photometric interpretation for g4 tiff: rp   zunsupported FillOrder: )r   r   r  z
/BlackIs1 z /K -1 /Rows )
r  r  r  r<  r  r  r  r  r  r  r  )remove_slice)r.   r/   )select_slicesmaskr  )r   r@   Indexedpaltransparencyr   rP   r  z/BlackIs1 true /Columns fp)	r  r  r  r<  r  r  r  r  r  ),r   EnvironmentErrorr=  r   r>  rA  rj  rI  r   rD  resizeRESAMPLEformatmodePIL_featurescheckconvertsizer   r\  r~  rC  r  rM  re  rS  tag_v2r   STRIPOFFSETSSTRIPBYTECOUNTSPHOTOMETRIC_INTERPRETATIONccitt_payload_location_from_pilrP  	FILLORDER	bytearray	enumerateTIFFBitRevTablelower_to_dataslice
_has_alphapalettesetattrclose)rc  rY  rR  r2  
is_pil_imgkeep_bytes_io_openjpeg_invertedimg_raw_dataimg_alteredr  r  r\  r<  r  r  colspacephotor  offsetlengthccittrawdata	fillorderr:  nalpha_channelr  s                             r+   rQ  rQ    sE    }RSSJ M'+L*S4+.!(+jj&
3'W5c5!"3<LL'''jj&
Kjjj1v::&LXX_!3!3I!> ,L(L
xx;<=#@kk&!
xxIIkk&!
xx= \[%@kk% 	d	 ;kk#88DAqDD -0(;88M*D::LK$?xx?*%6"S(V#%7"S( $S%7"S( #;CHH:!FGGa KK(--/" % -23%z!E K JJ&  00'83CJJ;;<=BCJJ>>?@AEJJIIJEHz! J5'R  =SANFFf%.:.?.?.GL

'@'@AI INa(6%l3DAq&5a&8LO 4$\2 #:9+!FGG!3ChKK( "% -&sx<'8'>'>'@&AA3m\][^_ K L
xx3/S(\2V	S/S(\2V	T	/S(aq)\NVc?| 4
  
 %S,]SDM	S,S(\2V-0[[-Dckk))$U 88<<-9l S
 ?

 %F#\aq@QDM 
T	,S(-0[[-Dckk))$Uaq)\NVc?| 4
  
 %S,]SDM	V	/S(\2V	U	.S(\2V.S(aq)\NVc?| 4
  
 %S,]SDM!#j	4B
xx3's-s;Ct$IIKKK%
	
 Kr*   c                   D    e Zd ZdZdededefdZddZd	ed
ededdfdZy)	temp_attrzM
    temporary change the attribute of an object using a context manager
    r`  fieldvaluec                 J    || _         || _        || _        d| _        d | _        y )NF)r`  r  r  exists	old_value)selfr`  r  r  s       r+   __init__ztemp_attr.__init__  s%    

"r*   r3  Nc                     t        | j                  | j                        r,d| _        t	        | j                  | j                        | _        t        | j                  | j                  | j                         y )NT)rh  r`  r  r  getattrr  r  r  )r  s    r+   	__enter__ztemp_attr.__enter__  sI    488TZZ(DK$TXXtzz:DN$**djj1r*   exctypeexcinstexctbc                     | j                   r,t        | j                  | j                  | j                         y t        | j                  | j                         y rb  )r  r  r`  r  r  delattr)r  r  r  r  s       r+   __exit__ztemp_attr.__exit__  s3    ;;DHHdjj$..9DHHdjj)r*   )r3  N)	r$   r%   r&   __doc__r   r>  r  r  r  r)   r*   r+   r  r    sG    #C # #C #2* *c *# *$ *r*   r  c                     | j                   t        j                     }| j                   t        j                     }t	        |      dk7  st	        |      dk7  rt        d      ||c\  }\  }||fS )z[
    returns the byte offset and length of the CCITT payload in the original TIFF data
    r   z;Transcoding multiple strips not supported by the PDF format)r  r   r  r  rS  rp  )rY  strip_offsetsstrip_bytesr  r  s        r+   r  r    sy     JJ;;<M**_<<=K 	Ma{q !I
 	

 	 IVy
 6>r*   c                 
    t               }t        j                   j                   j                   j                               } j                  d   dz   dz   j                  d   z  t        t        d      r/t        t        d      5  |j                  |dd       d	d	d	       nlt        j                  j                  d
t        dt        dt        f fd}t        t        j                  d|      5  |j                  |dd       d	d	d	       |j                  d       t        j                   |      }t#        |      \  }}|j                  |       |j%                  |      S # 1 sw Y   _xY w# 1 sw Y   kxY w)zN
    Convert the open PIL.Image imgdata to compressed CCITT Group4 data.

    r   r  r@   r   
STRIP_SIZEr  r  )r  r  Nr  tagr3  c                     t         j                  j                  d   t         j                  gt         j                  dgi}|j                  | | |            S )Nr   r   )r   ROWSPERSTRIPr  r  r  rP  )r  r  	overridesrY  pillow__getitem__tmp_strip_sizes      r+   __getitem__z)transcode_monochrome.<locals>.__getitem__V  sS    ,,chhqk//.1A,,qcI
 ==&7c&BCCr*   r  )r   r   	frombytesr  r  rJ  rh  r   r  saveImageFileDirectory_v2r  r   r'   objectr  rj  r  re  )	rY  newimgioimg2r  newimgr  r  r  r  s	   `      @@r+   transcode_monochromer  8  s@    yH
 ??388SXXs{{}=D hhqkAo!+chhqk9N-nEIIhv8ID FE
 ,AAMM	Dc 	D 	D 	D 11=+
 IIhv8ID
 MM!ZZ!F4V<NFFMM&==  7 FE
 
s   E-:E9-E69Fr  r  c                    t        | j                               }|r||= |r||   }| j                  dk(  rt        | j                  d   dz        }n=t        |      | j                  d   | j                  d   z  z  }| j                  d   |z  }t               }t        dt        |      |      D ]*  }|j                  d       |j                  ||||z           , |}t        g}t               \  }	}
}}d}|D ]  }|t        |g      z   }||	v r|}|j                  |	|          |
dt        z  dz
  k  r&|
|	|<   |
dz  }
|
|kD  r;|t        k  r2|dz  }d|z  dz
  }n$|j                  t               t               \  }	}
}}t        |g      } |r|j                  |	|          |j                  t               t        |      S )Nr  r   r@   r       r*   )r  rJ  r  r   r  rS  rangeextendLZW_CLEAR_TABLE_MARKERclear_tablerD  appendLZW_MAX_BITS_PER_CODELZW_EOD_MARKERpack_codes_into_bytes)rY  r  r  r  row_sizechannels_countdata_with_paddingr:  result_codestable	next_codebits_per_codemax_code_valuecurrent_sequencebytenext_sequences                   r+   _to_lzwdatar  m  s   
 S[[]#DL!
xx3a(Tsxx{SXXa['@A88A;/!1c$i*  '  a!h,!78 + D ++L6Am3E9m^(5$=8E!, &6 78 Q"771<<'0m$Q	~--BW2W!Q&M&'=&8A%=N ##$:;BM-?y-  %dV}/ 4 E"234' ..r*   codesc                    t               \  }}}}d}d}t               }t        %t        j                  | t        j                        } | D ]{  }||z  |z  }||z  }|dk\  r"|dz  }|j                  ||z	  dz         |dk\  r"|t        k(  rt               \  }}}}P|t        k7  sZ|dz  }||kD  se|t        k  so|dz  }d|z  dz
  }} |dkD  r|j                  |d|z
  z  dz         t        |      S )z
    Convert the list of result codes into a continuous byte stream, with codes packed as per the code bit-width.
    The bit-width starts at 9 bits and expands as needed.

    r   )dtyper@   r.  r   )
r  r  numpyarrayuint32r  r  r  r  rD  )	r  r  r  r  r  bufferbits_in_bufferoutputcodes	            r+   r   r     s     		FN[F E6M)T1-'!aNMM6^3t;< ! )):E-7Ay-^#NI>)m>S.S""#}"4!9   v!n"45=>=r*   c                      t        d      D  ci c]  } t        | g      |  }} t        dz   }t        }d|z  dz
  }||||fS c c} w )zK
    Reset the encoding table and coding state to initial conditions.

    r/  r   )r  rD  r  LZW_INITIAL_BITS_PER_CODE)r:  r  r  r  r  s        r+   r  r    sX     %*#J/JqUA3Z]JE/"I-M=(A-N)]N::	 0s   Akwargsc                    |dk(  rt        | fi |S |dk(  rt        |       S |dk(  rt        | fi |S | j                  dk(  r| j	                  d      } | j                  dk(  r| j	                  d      } |dk(  r-t               }| j                  |d	
       |j                         S |dk(  r-t               }| j                  |d
       |j                         S t        d| d      )Nr-   r  r0   r  r  r  rx  r.   r  )r  r/   JPEG2000zUnsupported image filter: "")		_to_zdatar  r  r  r  r   r  rH  r   )rY  rR  r  compressed_bytess       r+   r  r    s    }$'''''#C(({"3)&))
xx4kk#
xx6kk% {""9!&1((**{""9!*5((**
5l^1E
FFr*   c                     t        | j                               }|r||= |r||   }| j                  dk(  rt        | j                  d   dz        }n=t        |      | j                  d   | j                  d   z  z  }| j                  d   |z  }t               }t        dt        |      |      D ]*  }|j                  d       |j                  ||||z           , t        j                  |t        j                        S )Nr  r   r@   r   r  )level)r  rJ  r  r   r  rS  r  r  zlibcompressSETTINGSr#   )rY  r  r  r  r  r  r  r:  s           r+   r  r    s    
 S[[]#DL!
xx3a(Tsxx{SXXa['@A88A;/!1c$i*  '  a!h,!78 + ==*(2L2LMMr*   c                    | j                  d      }|j                         \  }}|dk(  r|dk(  ry||k(  ryt        &t        j                  |      dk7  j	                         S t	        d |j                         D              S )a  
    Return True if the image has any non-opaque alpha channel values.

    For the alpha band, `getextrema()` yields the min & max values across all pixels:
    - (255, 255): every pixel is fully opaque, so we can fast-return False.
    - (x, x) where x != 255: the channel is a flat non-opaque mask, so True.
    Otherwise we need to scan for any value different from 255 (using NumPy if available).
    Ar.  FTc              3   &   K   | ]	  }|d k7    yw)r.  Nr)   ).0cs     r+   	<genexpr>z_has_alpha.<locals>.<genexpr>,  s     9!8AqCx!8s   )
getchannel
getextremar  asarrayanyrJ  )rY  r  lohis       r+   r  r    s{     NN3'M%%'FB	SyR3Y	Rxm,388::9!6!6!8999r*   rb  )Nr,   N)NN)Xrq  rK  rG  loggingr!  dataclassesr   r   mathr   pathlibr   typingr   r   r	   r
   r   r   r   r   r   urllib.requestr   errorsr   image_datastructuresr   r   r   r   r  r   utilr   PILr   r   r   r   r  ImportError	PIL.Imager   LANCZOSr  AttributeErrorr   PIL.ImageCmsr   r(   r  r!   	getLoggerr$   rT  SUPPORTED_IMAGE_FILTERSr#  r  r  r  r  r  tuplefloatr>  rD  r]  boolrE  rI  rA  ri  r~  r@  rQ  r  r'   r  r  r  r  r   dictr  r  r  r  r)   r*   r+   <module>rE     s     	   !   
 
 
 # !   NN$!!H +,Hi
      
 
		8	$X ?<     +/U"U"
U" 5&
'U" 	)Z$
<=o%'	U"pGE Gd G>s >y2 >*th. *8 *4 c  g    t   $ /9
3	?*+( @D &*.	gC4'(g	z5(D#t;	<g g 5&
'	g
 gT* *2 c3h <2!j 2!U 2!n "&!%=/	=/$,=/ $,=/ 	=/@(# (5 (V
;U4s
+S#s:; 
;G* GK G3 G5 G> "&!%N	N$,N $,N 	N2:J :4 :m  EHOL	 	^$ H  Es6   )G2 6H H 2HH	HHH! H!